引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
配置文件
spring:data:mongodb:host: 127.0.0.1
database: test
port:27017# 也可以使用uri mongodb://127.0.0.1:27017/test
创建实体类
publicclassStudentimplementsSerializable{@IdprivateString studentId;privateString studentName;privateInteger studentAge;privateDouble studentScore;privateDate studentBirthday;publicStudent(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;}publicStudent(){}publicStringgetStudentId(){return studentId;}publicvoidsetStudentId(String studentId){this.studentId = studentId;}publicStringgetStudentName(){return studentName;}publicvoidsetStudentName(String studentName){this.studentName = studentName;}publicIntegergetStudentAge(){return studentAge;}publicvoidsetStudentAge(Integer studentAge){this.studentAge = studentAge;}publicDoublegetStudentScore(){return studentScore;}publicvoidsetStudentScore(Double studentScore){this.studentScore = studentScore;}publicDategetStudentBirthday(){return studentBirthday;}publicvoidsetStudentBirthday(Date studentBirthday){this.studentBirthday = studentBirthday;}@OverridepublicStringtoString(){return"Student{"+"studentId='"+ studentId +'\''+", studentName='"+ studentName +'\''+", studentAge="+ studentAge +", studentScore="+ studentScore +", studentBirthday="+ studentBirthday +'}';}}
dao层
1、JPA方式
/**
* @Author: acton_zhang
* @Date: 2023/5/9 12:41 上午
* @Version 1.0
* JPA方式
* 继承MongoRepository即可,不需要实现类
*/publicinterfaceStudentRepositoryextendsMongoRepository<Student,String>{}
测试:
importdata.dao.StudentRepository;importdata.domain.Student;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.domain.*;importjava.util.*;/**
* @Author: acton_zhang
* @Date: 2023/5/9 12:44 上午
* @Version 1.0
*/@SpringBootTestpublicclassStudentRepositoryTest{@AutowiredprivateStudentRepository studentRepository;/**
* 插入单条数据
*/@TestpublicvoidinsertOne(){Student student =newStudent("009","tom",18,88.2d,newDate());
studentRepository.insert(student);}/**
* 插入多条数据
*/@TestpublicvoidinsertMany(){Student student1 =newStudent("002","jerry",19,38.2d,newDate());Student student2 =newStudent("003","mike",20,78.2d,newDate());List<Student> list =newArrayList<>();
list.add(student1);
list.add(student2);
studentRepository.insert(list);}/**
* 修改数据
*/@Testpublicvoidupdate(){Optional<Student> op = studentRepository.findById("001");Student student = op.get();
student.setStudentAge(222);
studentRepository.save(student);}/**
* 查询数据
*/@Testpublicvoidquery(){//根据Id查询单个对象Optional<Student> stuOp = studentRepository.findById("001");System.out.println(stuOp.get());//根据字段查询单个对象Student student =newStudent();
student.setStudentAge(19);Optional<Student> stuOp1 = studentRepository.findOne(Example.of(student));System.out.println(stuOp1.get());//根据id列表查询多个对象Iterable<Student> itStu = studentRepository.findAllById(Arrays.asList(newString[]{"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 =newStudent();
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);}/**
* 其他操作
*/@Testpublicvoidother(){//countlong count = studentRepository.count();System.out.println(count);Student student =newStudent();
student.setStudentAge(18);long count1 = studentRepository.count(Example.of(student));System.out.println(count1);//existsboolean exists = studentRepository.exists(Example.of(student));System.out.println(exists);boolean b = studentRepository.existsById("001");System.out.println(b);}/**
* 删除操作
*/@Testpublicvoidremove(){//根据id删除单个对象
studentRepository.deleteById("001");//根据字段删除Student student =newStudent();
student.setStudentAge(20);
studentRepository.delete(student);//删除所有
studentRepository.deleteAll();//根据字段删除多个Student student1 =newStudent();
student1.setStudentName("jerry");List<Student> list =newArrayList<>();
list.add(student);
list.add(student1);
studentRepository.deleteAll(list);}}
2、MongoTemplate方式
dao接口:
publicinterfaceStudentDao{//插入单个对象voidaddOne(Student student);//根据id删除单个对象voiddeleteOneById(String studentId);//修改单个对象voidupdateOne(Student student);//根据id获取单个对象StudentfindOneById(String studentId);//获取全部学生List<Student>findAll();}
实现类:
publicclassStudentDaoImplimplementsStudentDao{@AutowiredprivateMongoTemplate mongoTemplate;@OverridepublicvoidaddOne(Student student){
mongoTemplate.save(student);}@OverridepublicvoiddeleteOneById(String studentId){Student stu = mongoTemplate.findById(studentId,Student.class);if(stu !=null)
mongoTemplate.remove(stu);}@OverridepublicvoidupdateOne(Student student){
mongoTemplate.save(student);}@OverridepublicStudentfindOneById(String studentId){return mongoTemplate.findById(studentId,Student.class);}@OverridepublicList<Student>findAll(){return mongoTemplate.findAll(Student.class);}}
测试类:
@SpringBootTestpublicclassStudentDaoTest{@AutowiredprivateStudentDao studentDao;@TestvoidaddOneStudent(){// 插入10行for(Integer count =0; count <10; count++){Student student =newStudent();
student.setStudentId("study_"+count);
student.setStudentName("Echo"+count);
student.setStudentAge(count);
student.setStudentScore(98.5-count);
student.setStudentBirthday(newDate());
studentDao.addOne(student);}}@TestvoiddeleteOneStudentByStudentId(){// 删除id为study_0的学生
studentDao.deleteOneById("study_0");}@TestvoidupdateOneStudent(){// 修改id为study_1的Student年龄为21Student student = studentDao.findOneById("study_1");
student.setStudentAge(21);
studentDao.updateOne(student);}@TestvoidgetOneStudentByStudentId(){System.out.println(studentDao.findOneById("study_1"));}@TestvoidgetAllStudent(){List<Student> studentList = studentDao.findAll();
studentList.forEach(System.out::println);}}
MongoTemplate
1、查询
is查询:
Query query =newQuery();// where...is... 相当于 where ? = ?
query.addCriteria(Criteria.where("数据库字段名").is("你的参数"));// findOne 返回的是一个对象 Class代表你的表对应的映射类
mongoTemplate.findOne(query,Class.class);// find 返回的是数组
mongoTemplate.find(query,Class.class);
in查询:
ArrayList<String> list =newArrayList<>();// list代表你的数据Query query =Query.query(Criteria.where("数据库字段").in(list));
mongoTemplate.find(query,Class.class);// 如果想要查询指定的数据是否在数据库的数组中,可以用以下方法Query query =Query.query(Criteria.where("数据库字段(数组)").is("你的数组"));
字符模糊查询:
Query query =Query.query(Criteria.where("name").regex("小"));
指定字段不返回:
query.fields().exclude("field");
数组中添加或删除一条数据:
Query query =Query.query(Criteria.where("_id").is("id"));Update update =newUpdate();// push方法可以在数组中添加一条数据// pull方法可以在数组中删除一条数据// update.pull()
update.push("字段名称","data");
mongoTemplate.updateFirst(query, update,Class.class);
批量添加:
ArrayList<Class> list =newArrayList<>();
mongoTemplate.insert(list,Class.class);
数组查询:
数组格式:
{
name:"小明",
age:13,
friends:[{
name:"小王",
age:12},{
name:"小李",
age:18}]}
当要查询朋友中姓名为小王时
Query query =newQuery();
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","小赵");
数字字符串排序操作
对数据库中数字字符串排序:
加上这一行就行了 亲身体验
query.collation(Collation.of("zh").numericOrdering(true));
还有根据字符串排序时又是顺序并不是我们所想的字典序,加上下面这个也ok
query.collation(Collation.of("zh"));
分页:
//分页
query.limit(10);//排序Sort sort=Sort.by(Sort.Direction.DESC,"timestamp");
query.with(sort);
criteria:
关键字解释eq等于,第一个参数是对象属性,第二个参数是值allEq参数为一个Map对象,相当于多个eq的叠加gt大于ge大于等于lt小于le小于等于between在两个值之间Expression.between(“age”,new Integer(10),new Integer(20));likelike查询inin查询
2、更新
User user =newUser();
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");
3、插入
List<User> list =newArrayList<>();User user=newUser();//
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);
4、删除
List<MongoDbJavaTest> list =newArrayList<>();User user=newUser();
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");
版权归原作者 吴声子夜歌 所有, 如有侵权,请联系我们删除。