当前位置:   article > 正文

SpringBoot——整合MongoDB详解_springboot mongodb

springboot mongodb

引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4

配置文件

spring:
  data:
    mongodb:
      host: 127.0.0.1
      database: test
      port: 27017
      # 也可以使用uri   mongodb://127.0.0.1:27017/test
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

创建实体类

public class Student implements Serializable{
    
    @Id
    private String studentId;
    
    private String studentName;
    
    private Integer studentAge;
    
    private Double studentScore;
    
    private Date studentBirthday;

    public Student(String studentId, String studentName, Integer studentAge, Double studentScore, Date studentBirthday) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentAge = studentAge;
        this.studentScore = studentScore;
        this.studentBirthday = studentBirthday;
    }

    public Student() {
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }

    public Double getStudentScore() {
        return studentScore;
    }

    public void setStudentScore(Double studentScore) {
        this.studentScore = studentScore;
    }

    public Date getStudentBirthday() {
        return studentBirthday;
    }

    public void setStudentBirthday(Date studentBirthday) {
        this.studentBirthday = studentBirthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId='" + studentId + '\'' +
                ", studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                ", studentScore=" + studentScore +
                ", studentBirthday=" + studentBirthday +
                '}';
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

dao层

1、JPA方式
/**
 * @Author: acton_zhang
 * @Date: 2023/5/9 12:41 上午
 * @Version 1.0
 * JPA方式
 * 继承MongoRepository即可,不需要实现类
 */
public interface StudentRepository extends MongoRepository<Student, String> {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

测试:

import data.dao.StudentRepository;
import data.domain.Student;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;


import java.util.*;

/**
 * @Author: acton_zhang
 * @Date: 2023/5/9 12:44 上午
 * @Version 1.0
 */
@SpringBootTest
public class StudentRepositoryTest {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 插入单条数据
     */
    @Test
    public void insertOne() {
        Student student = new Student("009", "tom", 18, 88.2d, new Date());
        studentRepository.insert(student);
    }

    /**
     * 插入多条数据
     */
    @Test
    public void insertMany() {
        Student student1 = new Student("002", "jerry", 19, 38.2d, new Date());
        Student student2 = new Student("003", "mike", 20, 78.2d, new Date());
        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        studentRepository.insert(list);
    }

    /**
     * 修改数据
     */
    @Test
    public void update() {
        Optional<Student> op = studentRepository.findById("001");
        Student student = op.get();
        student.setStudentAge(222);
        studentRepository.save(student);
    }

    /**
     * 查询数据
     */
    @Test
    public void query() {
        //根据Id查询单个对象
        Optional<Student> stuOp = studentRepository.findById("001");
        System.out.println(stuOp.get());

        //根据字段查询单个对象
        Student student = new Student();
        student.setStudentAge(19);
        Optional<Student> stuOp1 = studentRepository.findOne(Example.of(student));
        System.out.println(stuOp1.get());

        //根据id列表查询多个对象
        Iterable<Student> itStu = studentRepository.findAllById(Arrays.asList(new String[]{"001", "002"}));
        Iterator<Student> itor = itStu.iterator();
        while (itor.hasNext())
            System.out.println(itor.next());

        //查询所有
        List<Student> all = studentRepository.findAll();

        //查询所有并排序
        List<Student> all1 = studentRepository.findAll(Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
        for (Student stu : all1)
            System.out.println(stu);

        //根据条件查询所有并排序
        Student student1 = new Student();
        student1.setStudentName("tom");
        List<Student> all2 = studentRepository.findAll(Example.of(student1), Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
        for (Student stu : all2)
            System.out.println(stu);

        //根据条件查询所有并排序,且分页
        Pageable pageable = PageRequest.of(0, 2);
        Page<Student> all3 = studentRepository.findAll(pageable);
        List<Student> content = all3.getContent();
        for (Student stu : content)
            System.out.println(stu);
    }

    /**
     * 其他操作
     */
    @Test
    public void other() {
        //count
        long count = studentRepository.count();
        System.out.println(count);
        Student student = new Student();
        student.setStudentAge(18);
        long count1 = studentRepository.count(Example.of(student));
        System.out.println(count1);

        //exists
        boolean exists = studentRepository.exists(Example.of(student));
        System.out.println(exists);
        boolean b = studentRepository.existsById("001");
        System.out.println(b);
    }


    /**
     * 删除操作
     */
    @Test
    public void remove() {
        //根据id删除单个对象
        studentRepository.deleteById("001");

        //根据字段删除
        Student student = new Student();
        student.setStudentAge(20);
        studentRepository.delete(student);

        //删除所有
        studentRepository.deleteAll();

        //根据字段删除多个
        Student student1 = new Student();
        student1.setStudentName("jerry");
        List<Student> list = new ArrayList<>();
        list.add(student);
        list.add(student1);
        studentRepository.deleteAll(list);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
2、MongoTemplate方式

dao接口:

public interface StudentDao {

    //插入单个对象
    void addOne(Student student);

    //根据id删除单个对象
    void deleteOneById(String  studentId);

    //修改单个对象
    void updateOne(Student student);

    //根据id获取单个对象
    Student findOneById(String studentId);
    
    //获取全部学生
    List<Student> findAll();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

实现类:

public class StudentDaoImpl implements StudentDao {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void addOne(Student student) {
        mongoTemplate.save(student);
    }

    @Override
    public void deleteOneById(String studentId) {
        Student stu = mongoTemplate.findById(studentId, Student.class);
        if (stu != null)
            mongoTemplate.remove(stu);

    }

    @Override
    public void updateOne(Student student) {
        mongoTemplate.save(student);

    }

    @Override
    public Student findOneById(String studentId) {
        return mongoTemplate.findById(studentId, Student.class);
    }

    @Override
    public List<Student> findAll() {
        return mongoTemplate.findAll(Student.class);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

测试类:

@SpringBootTest
public class StudentDaoTest {

    @Autowired
    private StudentDao studentDao;

    @Test
    void addOneStudent(){
//        插入10行
        for (Integer count = 0; count < 10; count++) {
            Student student = new Student();
            student.setStudentId("study_"+count);
            student.setStudentName("Echo"+count);
            student.setStudentAge(count);
            student.setStudentScore(98.5-count);
            student.setStudentBirthday(new Date());
            studentDao.addOne(student);
        }
    }

    @Test
    void deleteOneStudentByStudentId(){
//        删除id为study_0的学生
        studentDao.deleteOneById("study_0");
    }

    @Test
    void updateOneStudent(){
//        修改id为study_1的Student年龄为21
        Student student = studentDao.findOneById("study_1");
        student.setStudentAge(21);
        studentDao.updateOne(student);

    }

    @Test
    void getOneStudentByStudentId(){
        System.out.println(studentDao.findOneById("study_1"));
    }

    @Test
    void getAllStudent(){
        List<Student> studentList = studentDao.findAll();
        studentList.forEach(System.out::println);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

MongoTemplate

1、查询

is查询:

Query query = new Query();
// where...is... 相当于 where ? = ?
query.addCriteria(Criteria.where("数据库字段名").is("你的参数"));
// findOne 返回的是一个对象 Class代表你的表对应的映射类
mongoTemplate.findOne(query, Class.class);
// find 返回的是数组
mongoTemplate.find(query, Class.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

in查询:

ArrayList<String> list = new ArrayList<>();
// list代表你的数据
Query query = Query.query(Criteria.where("数据库字段").in(list));
mongoTemplate.find(query, Class.class);


// 如果想要查询指定的数据是否在数据库的数组中,可以用以下方法
Query query = Query.query(Criteria.where("数据库字段(数组)").is("你的数组"));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

字符模糊查询

Query query = Query.query(Criteria.where("name").regex("小"));
  • 1

指定字段不返回:

query.fields().exclude("field");
  • 1

数组中添加或删除一条数据:

Query query = Query.query(Criteria.where("_id").is("id"));
Update update = new Update();
// push方法可以在数组中添加一条数据
// pull方法可以在数组中删除一条数据
// update.pull()
update.push("字段名称", "data");
mongoTemplate.updateFirst(query, update, Class.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

批量添加:

ArrayList<Class> list = new ArrayList<>();
mongoTemplate.insert(list, Class.class);
  • 1
  • 2

数组查询:

数组格式:
{
    name:"小明",
    age:13,
    friends:[
        {
            name:"小王",
            age:12
        },
        {
            name:"小李",
            age:18
        }
    ]
}


当要查询朋友中姓名为小王时
Query query = new Query();
query.addCriteria(Criteria.where("friends.$.name").is("小王"));
mongoTemplate.find(query, User.class);


同样更新时也是一样,但是注意,更新时查询条件需要添加
query.addCriteria(Criteria.where("friends").elemMatch(Criteria.where("name").is("小王"));
Update update = Update.update("friends.$.friends", "小赵");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

数字字符串排序操作

对数据库中数字字符串排序:
加上这一行就行了 亲身体验
query.collation(Collation.of("zh").numericOrdering(true));
还有根据字符串排序时又是顺序并不是我们所想的字典序,加上下面这个也ok
query.collation(Collation.of("zh"));
  • 1
  • 2
  • 3
  • 4
  • 5

分页:

//分页
query.limit(10);
//排序
Sort sort=Sort.by(Sort.Direction.DESC,"timestamp");
query.with(sort);
  • 1
  • 2
  • 3
  • 4
  • 5

criteria:

关键字解释
eq等于,第一个参数是对象属性,第二个参数是值
allEq参数为一个Map对象,相当于多个eq的叠加
gt大于
ge大于等于
lt小于
le小于等于
between在两个值之间Expression.between(“age”,new Integer(10),new Integer(20));
likelike查询
inin查询
2、更新
User user = new User();
user.setId("5d1312aeb1829c279c6c256b");
user.setName("admin");
user.setAddress("测试");

Query query = Query.query(Criteria.where("_id").is("5d1312aeb1829c279c6c256b"));
Update update = Update.update("name","zs");
//  更新一条数据
mongoTemplate.updateFirst(query,update, User.class);
mongoTemplate.updateFirst(query,update, "mongodb_user");
mongoTemplate.updateFirst(query,update, User.class,"mongodb_user");
//  更新多条数据
mongoTemplate.updateMulti(query,update, User.class);
mongoTemplate.updateMulti(query,update,"mongodb_user");
mongoTemplate.updateMulti(query,update, User.class,"mongodb_user");
//  更新数据,如果数据不存在就新增
mongoTemplate.upsert(query,update, User.class);
mongoTemplate.upsert(query,update,"mongodb_user");
mongoTemplate.upsert(query,update, User.class,"mongodb_user");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
3、插入
List<User> list = new ArrayList<>();
User user= new User();//
user.setName("admin");
user.setAddress("测试");
list.add(user);

//  保存对象到mongodb
mongoTemplate.save(user);
mongoTemplate.insert(user);
//  根据集合名称保存对象到mongodb
mongoTemplate.save(user,"mongodb_user");
mongoTemplate.insert(user,"mongodb_user");
//  根据集合名称保存list到mongodb
mongoTemplate.save(list,"mongodb_user");
mongoTemplate.insert(list,"mongodb_user");
mongoTemplate.insert(list,User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
4、删除
List<MongoDbJavaTest> list = new ArrayList<>();
User user= new User();
user.setId("5d1312aeb1829c279c6c256b");
list.add(user);

Query query = Query.query(Criteria.where("_id").in("5d1312aeb1829c279c6c256b","5d13133ab1829c29d02ce29c"));
//  根据条件删除
mongoTemplate.remove(query);
mongoTemplate.remove(user);
mongoTemplate.remove(User.class);
//  根据条件删除(可删除多条)
mongoTemplate.remove(query,User.class,"mongodb_user");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55955
推荐阅读
相关标签
  

闽ICP备14008679号