赞
踩
Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类
前面的基础流程应用依赖,创建实体类参考下这篇文章参考文本
- package com.example.mongodb.repository;
-
- import com.example.mongodb.entity.Student;
- import org.springframework.data.mongodb.repository.MongoRepository;
-
- public interface StudentRespostiory extends MongoRepository <Student,String>{
- }
然后我们在测试类中注入StudentRepository调用 MongoRepository类封装好的方法
- @Test
- public void create(){
- Student student=new Student();
- student.setName("mary");
- student.setEmail("mary@168.com");
- student.setAge(17);
- Object s1 = studentRespostiory.save(student);
- System.out.println("保存的对象:"+s1);
- }
通过.save()将依据创建好的对象存入数据库
我们在linux下查询

成功的添加了数据
- @Test
- public void findList(){
- List<Student> studentList = studentRespostiory.findAll();
- for (Student s:studentList) {
- System.out.println("查询记录:"+s);
- }
- }
结果

- @Test
- public void findById(){
- Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
- System.out.println("根据id查询"+student);
- }

- @Test
- public void findStudentList(){
- Student student = new Student();
- student.setAge(16);
- student.setName("jock");
- Example<Student> stExample= Example.of(student);
- List<Student> userList = studentRespostiory.findAll(stExample);
- System.out.println(userList);
- }
通过findAll查询数据记录但是我们要把封装好的条件对象stExample传入到这个方法中,先把封装好的对象用Example.of()处理

- @Test
- public void findStudentList(){
- //固定格式--模糊匹配规则
- ExampleMatcher matcher=ExampleMatcher.matching()
- .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
- .withIgnoreCase(true);
-
- Student student = new Student();
- student.setName("c");
- Example<Student> stExample = Example.of(student,matcher);
- List<Student> studentList = studentRespostiory.findAll(stExample);
- for (Student s:studentList) {
- System.out.println("查询记录:"+s);
- }
- }
和条件查询差不多只要传入模糊查询的匹配规则。
条件带分页
- @Test
- public void findPage(){
- Pageable pageable= PageRequest.of(0,3);
- Student student=new Student();
- student.setName("mary");
-
- Example<Student> stExample = Example.of(student);
- Page<Student> all = studentRespostiory.findAll(stExample, pageable);
- System.out.println(all);
-
- }
我们调用PageRequest.of(0,3)设置当前页是第一页 并且每一页记录数为3然后返回给pageable对象 在做查询的时候把这个pageable对象传入到查询方法中
结果
![]()
- @Test
- public void updata(){
- Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
- student.setName("DFP77");
- studentRespostiory.save(student);
- }
和插入数据方法一样但是这里如果有识别带有id值会根据id修改之前的值
查看数据库

- @Test
- public void del(){
- studentRespostiory.deleteById("62049665dd5a9245cc968271");
- }
调用方法传入id
Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类,按照Spring Data规范就可以了
SpringData 方法定义规范
1、不是随便声明的,而需要符合一定的规范
2、 查询方法以find | read | get开头
3、 涉及条件查询时,条件的属性用条件关键字连接
4、 要注意的是:条件属性首字母需要大写
5、 支持属性的级联查询,但若当前类有符合条件的属性则优先使用,而不使用级联属性,若需要使用级联属性,则属性之间使用_强制进行连接
这样我们在接口写的方法不需要我们自己实现,MongoRepository根据定义的规则自己帮我们实现方法。


Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。