JAVA代碼實(shí)現(xiàn)MongoDB動(dòng)態(tài)條件之分頁(yè)查詢
一、使用QueryByExampleExecutor
1. 繼承MongoRepository
public interface StudentRepository extends MongoRepository<Student, String> { }
2. 代碼實(shí)現(xiàn)
使用ExampleMatcher匹配器-----只支持字符串的模糊查詢,其他類型是完全匹配 Example封裝實(shí)體類和匹配器 使用QueryByExampleExecutor接口中的findAll方法public Page<Student> getListWithExample(StudentReqVO studentReqVO) { Sort sort = Sort.by(Sort.Direction.DESC, 'createTime'); Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Student student = new Student(); BeanUtils.copyProperties(studentReqVO, student); //創(chuàng)建匹配器,即如何使用查詢條件 ExampleMatcher matcher = ExampleMatcher.matching() //構(gòu)建對(duì)象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認(rèn)字符串匹配方式:模糊查詢 .withIgnoreCase(true) //改變默認(rèn)大小寫(xiě)忽略方式:忽略大小寫(xiě) .withMatcher('name', ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查詢 .withIgnorePaths('pageNum', 'pageSize'); //忽略屬性,不參與查詢 //創(chuàng)建實(shí)例 Example<Student> example = Example.of(student, matcher); Page<Student> students = studentRepository.findAll(example, pageable); return students;}
缺點(diǎn):
不支持過(guò)濾條件分組。即不支持過(guò)濾條件用 or(或) 來(lái)連接,所有的過(guò)濾條件,都是簡(jiǎn)單一層的用 and(并且) 連接 不支持兩個(gè)值的范圍查詢,如時(shí)間范圍的查詢二、MongoTemplate結(jié)合Query
實(shí)現(xiàn)一:使用Criteria封裝查詢條件
public Page<Student> getListWithCriteria(StudentReqVO studentReqVO) { Sort sort = Sort.by(Sort.Direction.DESC, 'createTime'); Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Query query = new Query(); //動(dòng)態(tài)拼接查詢條件 if (!StringUtils.isEmpty(studentReqVO.getName())){ Pattern pattern = 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())); } //計(jì)算總數(shù) long total = mongoTemplate.count(query, Student.class); //查詢結(jié)果集 List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class); Page<Student> studentPage = new PageImpl(studentList, pageable, total); return studentPage;}
實(shí)現(xiàn)二:使用Example和Criteria封裝查詢條件
public Page<Student> getListWithExampleAndCriteria(StudentReqVO studentReqVO) { Sort sort = Sort.by(Sort.Direction.DESC, 'createTime'); Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Student student = new Student(); BeanUtils.copyProperties(studentReqVO, student); //創(chuàng)建匹配器,即如何使用查詢條件 ExampleMatcher matcher = ExampleMatcher.matching() //構(gòu)建對(duì)象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認(rèn)字符串匹配方式:模糊查詢 .withIgnoreCase(true) //改變默認(rèn)大小寫(xiě)忽略方式:忽略大小寫(xiě) .withMatcher('name', ExampleMatcher.GenericPropertyMatchers.contains()) //標(biāo)題采用“包含匹配”的方式查詢 .withIgnorePaths('pageNum', 'pageSize'); //忽略屬性,不參與查詢 //創(chuàng)建實(shí)例 Example<Student> example = Example.of(student, matcher); Query query = new Query(Criteria.byExample(example)); if (studentReqVO.getCreateTime() != null){ query.addCriteria(Criteria.where('createTime').lte(studentReqVO.getCreateTime())); } //計(jì)算總數(shù) long total = mongoTemplate.count(query, Student.class); //查詢結(jié)果集 List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class); Page<Student> studentPage = new PageImpl(studentList, pageable, total); return studentPage;}
缺點(diǎn):
不支持返回固定字段
三、MongoTemplate結(jié)合BasicQuery
BasicQuery是Query的子類 支持返回固定字段public Page<Student> getListWithBasicQuery(StudentReqVO studentReqVO) { Sort sort = Sort.by(Sort.Direction.DESC, 'createTime'); Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); QueryBuilder queryBuilder = new QueryBuilder(); //動(dòng)態(tài)拼接查詢條件 if (!StringUtils.isEmpty(studentReqVO.getName())) { Pattern pattern = 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()); } Query query = new BasicQuery(queryBuilder.get().toString()); //計(jì)算總數(shù) long total = mongoTemplate.count(query, Student.class); //查詢結(jié)果集條件 BasicDBObject fieldsObject = new BasicDBObject(); //id默認(rèn)有值,可不指定 fieldsObject.append('id', 1) //1查詢,返回?cái)?shù)據(jù)中有值;0不查詢,無(wú)值.append('name', 1); query = new BasicQuery(queryBuilder.get().toString(), fieldsObject.toJson()); //查詢結(jié)果集 List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class); Page<Student> studentPage = new PageImpl(studentList, pageable, total); return studentPage;}
四、MongoTemplate結(jié)合Aggregation
使用Aggregation聚合查詢 支持返回固定字段 支持分組計(jì)算總數(shù)、求和、平均值、最大值、最小值等等public Page<Student> getListWithAggregation(StudentReqVO studentReqVO) { Sort sort = Sort.by(Sort.Direction.DESC, 'createTime'); Pageable pageable = PageRequest.of(studentReqVO.getPageNum(), studentReqVO.getPageSize(), sort); Integer pageNum = studentReqVO.getPageNum(); Integer pageSize = studentReqVO.getPageSize(); List<AggregationOperation> operations = new ArrayList<>(); if (!StringUtils.isEmpty(studentReqVO.getName())) { Pattern pattern = Pattern.compile('^.*' + studentReqVO.getName() + '.*$', Pattern.CASE_INSENSITIVE); Criteria criteria = Criteria.where('name').regex(pattern); operations.add(Aggregation.match(criteria)); } if (null != studentReqVO.getSex()) { operations.add(Aggregation.match(Criteria.where('sex').is(studentReqVO.getSex()))); } long totalCount = 0; //獲取滿足添加的總頁(yè)數(shù) if (null != operations && operations.size() > 0) { Aggregation aggregationCount = Aggregation.newAggregation(operations); //operations為空,會(huì)報(bào)錯(cuò) AggregationResults<Student> resultsCount = mongoTemplate.aggregate(aggregationCount, 'student', Student.class); totalCount = resultsCount.getMappedResults().size(); } else { List<Student> 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')); Aggregation aggregation = Aggregation.newAggregation(operations); AggregationResults<Student> results = mongoTemplate.aggregate(aggregation, 'student', Student.class); //查詢結(jié)果集 Page<Student> studentPage = new PageImpl(results.getMappedResults(), pageable, totalCount); return studentPage;}
以上就是JAVA代碼實(shí)現(xiàn)MongoDB動(dòng)態(tài)條件之分頁(yè)查詢的詳細(xì)內(nèi)容,更多關(guān)于JAVA 實(shí)現(xiàn)MongoDB分頁(yè)查詢的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP中常用的22個(gè)FSO文件操作函數(shù)整理2. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)3. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp4. .Net core 的熱插拔機(jī)制的深入探索及卸載問(wèn)題求救指南5. SharePoint Server 2019新特性介紹6. html清除浮動(dòng)的6種方法示例7. asp的SQL語(yǔ)句中and和or同時(shí)使用的注意事項(xiàng)8. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析10. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程
