SpringBoot整合MongoDB(MongoRepository+MongoTemplate)

说 明:

SpringBoot 对mongodb操作存在两种操作方式,一种是MongoRepository,一种是MongoTemplate。

准备

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
    </dependencies>

YML文件配置

spring:
  data:
    mongodb:
      host: 127.0.0.1
      port: 27017
      username: admin
      password: admin
      authentication-database: admin
      database: monge_demo

MongoTemplate 方式实现

Bean 类

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@Document(collection = "student")
public class Student {

    private String id;
    private String name;
    private String unicode;
}
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.List;

@Data
@Document(collection = "teacher")
public class Teacher {

    private String id;
    private String name;
    private String project;
    private List<Student> students;
}

MongoTemplate CRUD 操作

import cn.hutool.core.lang.UUID;
import com.example.demo.domain.Student;
import com.example.demo.domain.Teacher;
import com.example.demo.util.MongoUtil;
import com.example.demo.util.PageHelper;
import com.mongodb.client.result.UpdateResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongodbApplicationTests {

    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private MongoUtil mongoUtil;

    @Test
    public void addStudent() {
        int a = 1;
        while (a <= 100) {
            Student student = new Student();
            student.setName("name" + a);
            student.setUnicode(UUID.randomUUID().toString());
            Student insert = mongoTemplate.insert(student);
            System.out.println(insert);
            a++;
        }
    }


    @Test
    public void findByName() {
        Query query = new Query(Criteria.where("name").is("name1"));
        List<Student> students = mongoTemplate.find(query, Student.class);
        System.out.println(students);
    }

    @Test
    public void findByNameAndUnicode() {
//        Query query = new Query(Criteria.where("name").is("name1").and("unicode").is("e24928f8-ef7a-479d-8211-fb4e01c344f5"));
        Student student = new Student();
        student.setName("name1");
        student.setUnicode("e24928f8-ef7a-479d-8211-fb4e01c344f5");
        Query query = new Query(Criteria.byExample(student));
        List<Student> students = mongoTemplate.find(query, Student.class);
        System.out.println(students);
    }

    @Test
    public void addTeacher() {
        List<String> str = new ArrayList<>();
        str.add("name1");
        str.add("name2");
        Query query = new Query(Criteria.where("name").in(str));
        List<Student> students = mongoTemplate.find(query, Student.class);
        int a = 1;
        while (a < 100) {
            Teacher teacher = new Teacher();
            teacher.setName("teacher");
            teacher.setProject("project" + a);
            teacher.setStudents(students);
            Teacher insert = mongoTemplate.insert(teacher);
            a++;
        }
    }

    /**
     * 查询list中对象的值
     */
    @Test
    public void findTeacher() {
        Query query = new Query(Criteria.where("students.name").is("name1").and("project").is("project1"));
        List<Teacher> teachers = mongoTemplate.find(query, Teacher.class);
        System.out.println(teachers);
    }

    /**
     * 分页查询
     */
    @Test
    public void findByPage() {
//        Query query = new Query(Criteria.where("students.name").is("name1").and("project").is("project1"));
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("teacher3"));
        long count = mongoTemplate.count(query, Teacher.class);
        //query.with(Sort.by(Sort.Direction.DESC, "time"));
        mongoUtil.start(1, 5, query);
        List<Teacher> teachers = mongoTemplate.find(query, Teacher.class);

        PageHelper pageHelper = mongoUtil.pageHelper(count, teachers);
        System.out.println(pageHelper);
    }

    /**
     * 分页查询
     */
    @Test
    public void findByPageAuto() {
//        Query query = new Query(Criteria.where("students.name").is("name1").and("project").is("project1"));
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("teacher3"));
        long count = mongoTemplate.count(query, Teacher.class);
        //query.with(Sort.by(Sort.Direction.DESC, "time"));
        mongoUtil.start(1, 5, query);
        List<Teacher> teachers = mongoTemplate.find(query, Teacher.class);

        PageHelper pageHelper = mongoUtil.pageHelper(count, teachers);
        System.out.println(pageHelper);
    }

    /**
     * 更新操作
     */
    @Test
    public void update() {
        Query query = new Query();
        query.addCriteria(Criteria.where("project").is("project2"));
        Update update = new Update();
//        //直接更新
//        update.set("students", "更新成功");
//        //文档不存在的话会插入一条新的记录
//        update.setOnInsert("students", "更新成功1");
//        //移除这个键
//        update.unset("students");
        //加入到一个集合中,不会重复
//        update.addToSet("students", "更新成功3");
        //需要传值,会清空其他属性
//        update.addToSet("students");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Teacher.class);
        System.out.println(updateResult);
    }

两个分页查询的工具类如下:

package com.example.demo.util;

import lombok.Data;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.regex.Pattern;

/**
 */
@Data
@Component
public class MongoUtil<T> {
    public Integer pageSize;
    private Integer currentPage;


    public void start(Integer currentPage, Integer pageSize, Query query) {
        pageSize = pageSize == 0 ? 10 : pageSize;
        query.limit(pageSize);
        query.skip((currentPage - 1) * pageSize);
        this.pageSize = pageSize;
        this.currentPage = currentPage;
    }

    public PageHelper pageHelper(long total, List<T> list) {
        return new PageHelper(this.currentPage, total, this.pageSize, list);
    }

    public PageHelper pageHelper(List<T> list) {
        return new PageHelper(this.currentPage, this.pageSize, list);
    }

    public PageHelper pageHelper(long currentPage, long total, long pageSize, List<T> list) {
        return new PageHelper(currentPage, total, pageSize, list);
    }

    public PageHelper pageHelper(long currentPage, long pageSize, List<T> list) {
        return new PageHelper(currentPage, pageSize, list);
    }


    /**
     * 用于模糊查询忽略大小写
     *
     * @param string
     * @return
     */
    public Pattern getPattern(String string) {
        Pattern pattern = Pattern.compile("^.*" + string + ".*$", Pattern.CASE_INSENSITIVE);
        return pattern;
    }
}

package com.example.demo.util;

import lombok.Data;

import java.util.List;

/**
 */
@Data
public class PageHelper<T> {
    private long currentPage;
    private long total;
    private long pageSize;
    private List<T> list;

    public PageHelper(long pageNum, long total, long pageSize, List<T> list) {
        this.currentPage = pageNum;
        this.total = total;
        this.pageSize = pageSize;
        this.list = list;
    }

    public PageHelper(long pageNum, long pageSize, List<T> list) {
        this.currentPage = pageNum;
        this.pageSize = pageSize;
        this.list = list;
    }
}

MongoRepository 方式实现

Bean 类

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Article {
    /**
     * 文章id
     */
    @Id
    private Long id;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 文章标题
     */
    private String title;

    /**
     * 文章内容
     */
    private String content;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 点赞数量
     */
    private Long thumbUp;

    /**
     * 访客数量
     */
    private Long visits;
}

MongoRepository CRUD操作


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.example.demo.dao.ArticleRepository;
import com.example.demo.domain.Article;
import com.example.demo.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@Service
public class ArticleRepositoryTest {
    @Autowired
    private ArticleRepository articleRepo;

    @Resource
    private MongoTemplate mongoTemplate;

    private static Snowflake snowflake = IdUtil.createSnowflake(1, 1);


    /**
     * 测试新增
     */
    @Test
    public void testSave() {

        Article article = new Article();
        article.setTitle("1");
        article.setUpdateTime(DateUtil.date());
        article.setContent("haohao大是大非接口");
        article.setCreateTime(DateUtil.date());
        article.setId(1L);
        article.setThumbUp(2L);
        article.setUserId(45L);
        article.setVisits(444L);
        articleRepo.save(article);

        log.info("【article】= {}", JSONUtil.toJsonStr(article));
    }

    /**
     * 测试批量新增列表
     */
    @Test
    public void testSaveList() {
        List<Article> articles = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            Article article = new Article();
            article.setTitle("1");
            article.setUpdateTime(DateUtil.date());
            article.setContent("haohao大是大非接口");
            article.setCreateTime(DateUtil.date());
            article.setId(1L+i);
            article.setThumbUp(2L+i);
            article.setUserId(45L+i);
            article.setVisits(444L+i);
            articles.add(article);
        }
        articleRepo.saveAll(articles);

        log.info("【articles】= {}", JSONUtil.toJsonStr(articles.stream().map(Article::getId).collect(Collectors.toList())));
    }

    /**
     * 测试更新
     */
    @Test
    public void testUpdate() {

        try {
            articleRepo.findById(1L).ifPresent(article -> {
                article.setTitle(article.getTitle() + "更新之后的标题");
                article.setUpdateTime(DateUtil.date());
                articleRepo.save(article);
                log.info("【article】= {}", JSONUtil.toJsonStr(article));
            });
        }catch (Exception ex){
        }
    }

    /**
     * 测试删除
     */
    @Test
    public void testDelete() {
        // 根据主键删除
        try {
            articleRepo.deleteById(1L);
        }catch (Exception ex){

        }

//
//        // 全部删除
//        articleRepo.deleteAll();
    }

    /**
     * 测试分页排序查询
     */
    @Test
    public void testQuery() {
        Sort sort = Sort.by("thumbUp", "updateTime").descending();

        Pageable pageable = PageRequest.of(0, 5, sort);
        Article article1 = new Article();
        Example<Article> userExample = Example.of(article1);
        Page<Article> all = articleRepo.findAll(userExample,pageable);
        log.info("【总页数】= {}", all.getTotalPages());
        log.info("【总条数】= {}", all.getTotalElements());
        log.info("【当前页数据】= {}", JSONUtil.toJsonStr(all.getContent().stream().map(article -> "文章标题:"
                + article.getTitle() + "点赞数:"
                + article.getThumbUp() + "更新时间:" + article.getUpdateTime()).collect(Collectors.toList())));
    }
}

上述就是两种方式的实现,希望能帮大家入个门。


版权声明:本文为houxian1103原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。