您好,登錄后才能下訂單哦!
這篇文章主要講解了JAVA如何實現(xiàn)MongoDB動態(tài)條件的分頁查詢,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
一、使用QueryByExampleExecutor
1. 繼承MongoRepository
public interface StudentRepository extends MongoRepository<Student, String> { }
2. 代碼實現(xiàn)
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)建對象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認(rèn)字符串匹配方式:模糊查詢 .withIgnoreCase(true) //改變默認(rèn)大小寫忽略方式:忽略大小寫 .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查詢 .withIgnorePaths("pageNum", "pageSize"); //忽略屬性,不參與查詢 //創(chuàng)建實例 Example<Student> example = Example.of(student, matcher); Page<Student> students = studentRepository.findAll(example, pageable); return students; }
缺點(diǎn):
二、MongoTemplate結(jié)合Query
實現(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(); //動態(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())); } //計算總數(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; }
實現(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)建對象 .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認(rèn)字符串匹配方式:模糊查詢 .withIgnoreCase(true) //改變默認(rèn)大小寫忽略方式:忽略大小寫 .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //標(biāo)題采用“包含匹配”的方式查詢 .withIgnorePaths("pageNum", "pageSize"); //忽略屬性,不參與查詢 //創(chuàng)建實例 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())); } //計算總數(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
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(); //動態(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()); //計算總數(shù) long total = mongoTemplate.count(query, Student.class); //查詢結(jié)果集條件 BasicDBObject fieldsObject = new BasicDBObject(); //id默認(rèn)有值,可不指定 fieldsObject.append("id", 1) //1查詢,返回數(shù)據(jù)中有值;0不查詢,無值 .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
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; //獲取滿足添加的總頁數(shù) if (null != operations && operations.size() > 0) { Aggregation aggregationCount = Aggregation.newAggregation(operations); //operations為空,會報錯 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; }
看完上述內(nèi)容,是不是對JAVA如何實現(xiàn)MongoDB動態(tài)條件的分頁查詢有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。