JAVA代码实现MongoDB动态条件之分页查询
一、使用QueryByExampleExecutor
1.继承MongoRepository
publicinterfaceStudentRepositoryextendsMongoRepository{ }
2.代码实现
- 使用ExampleMatcher匹配器-----只支持字符串的模糊查询,其他类型是完全匹配
- Example封装实体类和匹配器
- 使用QueryByExampleExecutor接口中的findAll方法
publicPagegetListWithExample(StudentReqVOstudentReqVO){ Sortsort=Sort.by(Sort.Direction.DESC,"createTime"); Pageablepageable=PageRequest.of(studentReqVO.getPageNum(),studentReqVO.getPageSize(),sort); Studentstudent=newStudent(); BeanUtils.copyProperties(studentReqVO,student); //创建匹配器,即如何使用查询条件 ExampleMatchermatcher=ExampleMatcher.matching()//构建对象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式:模糊查询 .withIgnoreCase(true)//改变默认大小写忽略方式:忽略大小写 .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())//采用“包含匹配”的方式查询 .withIgnorePaths("pageNum","pageSize");//忽略属性,不参与查询 //创建实例 Example example=Example.of(student,matcher); Page students=studentRepository.findAll(example,pageable); returnstudents; }
缺点:
- 不支持过滤条件分组。即不支持过滤条件用or(或)来连接,所有的过滤条件,都是简单一层的用and(并且)连接
- 不支持两个值的范围查询,如时间范围的查询
二、MongoTemplate结合Query
实现一:使用Criteria封装查询条件
publicPagegetListWithCriteria(StudentReqVOstudentReqVO){ Sortsort=Sort.by(Sort.Direction.DESC,"createTime"); Pageablepageable=PageRequest.of(studentReqVO.getPageNum(),studentReqVO.getPageSize(),sort); Queryquery=newQuery(); //动态拼接查询条件 if(!StringUtils.isEmpty(studentReqVO.getName())){ Patternpattern=Pattern.compile("^.*"+studentReqVO.getName()+".*$",Pattern.CASE_INSENSITIVE); query.addCriteria(Criteria.where("name").regex(pattern)); } if(studentReqVO.getSex()!=null){ query.addCriteria(Criteria.where("sex").is(studentReqVO.getSex())); } if(studentReqVO.getCreateTime()!=null){ query.addCriteria(Criteria.where("createTime").lte(studentReqVO.getCreateTime())); } //计算总数 longtotal=mongoTemplate.count(query,Student.class); //查询结果集 List studentList=mongoTemplate.find(query.with(pageable),Student.class); Page studentPage=newPageImpl(studentList,pageable,total); returnstudentPage; }
实现二:使用Example和Criteria封装查询条件
publicPagegetListWithExampleAndCriteria(StudentReqVOstudentReqVO){ Sortsort=Sort.by(Sort.Direction.DESC,"createTime"); Pageablepageable=PageRequest.of(studentReqVO.getPageNum(),studentReqVO.getPageSize(),sort); Studentstudent=newStudent(); BeanUtils.copyProperties(studentReqVO,student); //创建匹配器,即如何使用查询条件 ExampleMatchermatcher=ExampleMatcher.matching()//构建对象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式:模糊查询 .withIgnoreCase(true)//改变默认大小写忽略方式:忽略大小写 .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains())//标题采用“包含匹配”的方式查询 .withIgnorePaths("pageNum","pageSize");//忽略属性,不参与查询 //创建实例 Example example=Example.of(student,matcher); Queryquery=newQuery(Criteria.byExample(example)); if(studentReqVO.getCreateTime()!=null){ query.addCriteria(Criteria.where("createTime").lte(studentReqVO.getCreateTime())); } //计算总数 longtotal=mongoTemplate.count(query,Student.class); //查询结果集 List studentList=mongoTemplate.find(query.with(pageable),Student.class); Page studentPage=newPageImpl(studentList,pageable,total); returnstudentPage; }
缺点:
不支持返回固定字段
三、MongoTemplate结合BasicQuery
- BasicQuery是Query的子类
- 支持返回固定字段
publicPagegetListWithBasicQuery(StudentReqVOstudentReqVO){ Sortsort=Sort.by(Sort.Direction.DESC,"createTime"); Pageablepageable=PageRequest.of(studentReqVO.getPageNum(),studentReqVO.getPageSize(),sort); QueryBuilderqueryBuilder=newQueryBuilder(); //动态拼接查询条件 if(!StringUtils.isEmpty(studentReqVO.getName())){ Patternpattern=Pattern.compile("^.*"+studentReqVO.getName()+".*$",Pattern.CASE_INSENSITIVE); queryBuilder.and("name").regex(pattern); } if(studentReqVO.getSex()!=null){ queryBuilder.and("sex").is(studentReqVO.getSex()); } if(studentReqVO.getCreateTime()!=null){ queryBuilder.and("createTime").lessThanEquals(studentReqVO.getCreateTime()); } Queryquery=newBasicQuery(queryBuilder.get().toString()); //计算总数 longtotal=mongoTemplate.count(query,Student.class); //查询结果集条件 BasicDBObjectfieldsObject=newBasicDBObject(); //id默认有值,可不指定 fieldsObject.append("id",1)//1查询,返回数据中有值;0不查询,无值 .append("name",1); query=newBasicQuery(queryBuilder.get().toString(),fieldsObject.toJson()); //查询结果集 List studentList=mongoTemplate.find(query.with(pageable),Student.class); Page studentPage=newPageImpl(studentList,pageable,total); returnstudentPage; }
四、MongoTemplate结合Aggregation
- 使用Aggregation聚合查询
- 支持返回固定字段
- 支持分组计算总数、求和、平均值、最大值、最小值等等
publicPagegetListWithAggregation(StudentReqVOstudentReqVO){ Sortsort=Sort.by(Sort.Direction.DESC,"createTime"); Pageablepageable=PageRequest.of(studentReqVO.getPageNum(),studentReqVO.getPageSize(),sort); IntegerpageNum=studentReqVO.getPageNum(); IntegerpageSize=studentReqVO.getPageSize(); List operations=newArrayList<>(); if(!StringUtils.isEmpty(studentReqVO.getName())){ Patternpattern=Pattern.compile("^.*"+studentReqVO.getName()+".*$",Pattern.CASE_INSENSITIVE); Criteriacriteria=Criteria.where("name").regex(pattern); operations.add(Aggregation.match(criteria)); } if(null!=studentReqVO.getSex()){ operations.add(Aggregation.match(Criteria.where("sex").is(studentReqVO.getSex()))); } longtotalCount=0; //获取满足添加的总页数 if(null!=operations&&operations.size()>0){ AggregationaggregationCount=Aggregation.newAggregation(operations);//operations为空,会报错 AggregationResults resultsCount=mongoTemplate.aggregate(aggregationCount,"student",Student.class); totalCount=resultsCount.getMappedResults().size(); }else{ List list=mongoTemplate.findAll(Student.class); totalCount=list.size(); } operations.add(Aggregation.skip((long)pageNum*pageSize)); operations.add(Aggregation.limit(pageSize)); operations.add(Aggregation.sort(Sort.Direction.DESC,"createTime")); Aggregationaggregation=Aggregation.newAggregation(operations); AggregationResults results=mongoTemplate.aggregate(aggregation,"student",Student.class); //查询结果集 Page studentPage=newPageImpl(results.getMappedResults(),pageable,totalCount); returnstudentPage; }
以上就是JAVA代码实现MongoDB动态条件之分页查询的详细内容,更多关于JAVA实现MongoDB分页查询的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。