Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类
前面的基础流程应用依赖,创建实体类参考下这篇文章参考文本
1.创建接口继承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类封装好的方法
2.添加记录方法
@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下查询
成功的添加了数据
3.查询所有数据
@Test
public void findList(){
List<Student> studentList = studentRespostiory.findAll();
for (Student s:studentList) {
System.out.println("查询记录:"+s);
}
}
结果
4.根据id查询
@Test
public void findById(){
Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
System.out.println("根据id查询"+student);
}
5.添加查询
@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()处理
6.模糊查询
@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);
}
}
和条件查询差不多只要传入模糊查询的匹配规则。
7.分页查询
条件带分页
@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);
}
结果
8.更新数据
@Test
public void updata(){
Student student = studentRespostiory.findById("62049665dd5a9245cc968271").get();
student.setName("DFP77");
studentRespostiory.save(student);
}
和插入数据方法一样但是这里如果有识别带有id值会根据id修改之前的值
查看数据库
9.删除
@Test
public void del(){
studentRespostiory.deleteById("62049665dd5a9245cc968271");
}
调用方法传入id