最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JAVA代碼實現(xiàn)MongoDB動態(tài)條件之分頁查詢

 更新時間:2020年07月15日 15:05:15   作者:時間-海  
這篇文章主要介紹了JAVA如何實現(xiàn)MongoDB動態(tài)條件之分頁查詢,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下

一、使用QueryByExampleExecutor

1. 繼承MongoRepository

public interface StudentRepository extends MongoRepository<Student, String> {
  
}

2. 代碼實現(xiàn)

  • 使用ExampleMatcher匹配器-----只支持字符串的模糊查詢,其他類型是完全匹配
  • Example封裝實體類和匹配器
  • 使用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)建對象
      .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;
}

缺點:

  • 不支持過濾條件分組。即不支持過濾條件用 or(或) 來連接,所有的過濾條件,都是簡單一層的用 and(并且) 連接
  • 不支持兩個值的范圍查詢,如時間范圍的查詢

二、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;
}

缺點:

不支持返回固定字段

三、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();

  //動態(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

  • 使用Aggregation聚合查詢
  • 支持返回固定字段
  • 支持分組計算總數(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;
  //獲取滿足添加的總頁數(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;
}

以上就是JAVA代碼實現(xiàn)MongoDB動態(tài)條件之分頁查詢的詳細(xì)內(nèi)容,更多關(guān)于JAVA 實現(xiàn)MongoDB分頁查詢的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java、spring、springboot中整合Redis的詳細(xì)講解

    java、spring、springboot中整合Redis的詳細(xì)講解

    這篇文章主要介紹了java、spring、springboot中整合Redis的詳細(xì)講解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Java線程取消的三種方式

    Java線程取消的三種方式

    文章介紹了 Java 線程取消的 3 種方式,不推薦使用 stop 方法和 volatile 設(shè)標(biāo)記位停止線程,線程中斷機制是協(xié)作式的,一個線程請求中斷,另一線程響應(yīng),線程可檢查自身中斷狀態(tài)或捕獲 InterruptedException 來合適處理以響應(yīng)中斷,確保安全有序停止,避免資源泄露等問題
    2024-12-12
  • 淺談Spring與SpringMVC父子容器的關(guān)系與初始化

    淺談Spring與SpringMVC父子容器的關(guān)系與初始化

    這篇文章主要介紹了淺談Spring與SpringMVC父子容器的關(guān)系與初始化,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Java中LinkedHashSet的底層機制詳解

    Java中LinkedHashSet的底層機制詳解

    這篇文章主要介紹了Java中LinkedHashSet的底層機制解讀,   LinkedHashSet是具有可預(yù)知迭代順序的Set接口的哈希表和鏈接列表實現(xiàn),此實現(xiàn)與HashSet的不同之處在于,后者維護著一個運行于所有條目的雙重鏈接列表,需要的朋友可以參考下
    2023-09-09
  • Java隨機值設(shè)置(java.util.Random類或Math.random方法)

    Java隨機值設(shè)置(java.util.Random類或Math.random方法)

    在編程中有時我們需要生成一些隨機的字符串作為授權(quán)碼、驗證碼等,以確保數(shù)據(jù)的安全性和唯一性,這篇文章主要給大家介紹了關(guān)于Java隨機值設(shè)置的相關(guān)資料,主要用的是java.util.Random類或Math.random()方法,需要的朋友可以參考下
    2024-08-08
  • 詳解Spring中Bean的作用域與生命周期

    詳解Spring中Bean的作用域與生命周期

    Spring作為當(dāng)前Java最流行、最強大的輕量級框架,受到了程序員的熱烈歡迎。準(zhǔn)確的了解Spring?Bean的作用域與生命周期是非常必要的。這篇文章將問你詳解一下Bean的作用域與生命周期,需要的可以參考一下
    2021-12-12
  • java求數(shù)組第二大元素示例

    java求數(shù)組第二大元素示例

    這篇文章主要介紹了java求數(shù)組第二大元素示例,需要的朋友可以參考下
    2014-04-04
  • Spring Security加密和匹配及原理解析

    Spring Security加密和匹配及原理解析

    我們開發(fā)時進行密碼加密,可用的加密手段有很多,比如對稱加密、非對稱加密、信息摘要等,本篇文章給大家介紹Spring Security加密和匹配及原理解析,感興趣的朋友一起看看吧
    2023-10-10
  • Java并發(fā)編程之創(chuàng)建線程

    Java并發(fā)編程之創(chuàng)建線程

    這篇文章主要介紹了Java并發(fā)編程中創(chuàng)建線程的方法,Java中如何創(chuàng)建線程,讓線程去執(zhí)行一個子任務(wù),感興趣的小伙伴們可以參考一下
    2016-02-02
  • Java8的Lambda和排序

    Java8的Lambda和排序

    這篇文章主要介紹了Java8的Lambda和排序,對數(shù)組和集合進行排序是Java 8 lambda令人驚奇的一個應(yīng)用,我們可以實現(xiàn)一個Comparators來實現(xiàn)各種排序,下面文章將有案例詳細(xì)說明,想要了解得小伙伴可以參考一下
    2021-11-11

最新評論

翁牛特旗| 昌江| 柘荣县| 庆安县| 余庆县| 马龙县| 东乌珠穆沁旗| 上杭县| 尖扎县| 米泉市| 万全县| 广平县| 海城市| 五峰| 襄垣县| 丰镇市| 军事| 九龙城区| 仲巴县| 夹江县| 静安区| 托克逊县| 博乐市| 安溪县| 正镶白旗| 简阳市| 鸡西市| 积石山| 新津县| 肃宁县| 甘孜县| 黔西| 兴化市| 玛沁县| 淮安市| 凌云县| 台湾省| 麟游县| 东宁县| 甘德县| 卢龙县|