JAVA代码实现MongoDB动态条件之分页查询

 更新时间:2020年07月15日 15:05:15   作者:时间-海  
这篇文章主要介绍了JAVA如何实现MongoDB动态条件之分页查询,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下

一、使用QueryByExampleExecutor

1. 继承MongoRepository

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

2. 代码实现

  • 使用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);

  //创建匹配器,即如何使用查询条件
  ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
      .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
      .withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
      .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查询
      .withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询

  //创建实例
  Example<Student> example = Example.of(student, matcher);
  Page<Student> students = studentRepository.findAll(example, pageable);

  return students;
}

缺点:

  • 不支持过滤条件分组。即不支持过滤条件用 or(或) 来连接,所有的过滤条件,都是简单一层的用 and(并且) 连接
  • 不支持两个值的范围查询,如时间范围的查询

二、MongoTemplate结合Query

实现一:使用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();

  //动态拼接查询条件
  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()));
  }

  //计算总数
  long total = mongoTemplate.count(query, Student.class);

  //查询结果集
  List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
  Page<Student> studentPage = new PageImpl(studentList, pageable, total);
  return studentPage;
}

实现二:使用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);

  //创建匹配器,即如何使用查询条件
  ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
      .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
      .withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
      .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //标题采用“包含匹配”的方式查询
      .withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询

  //创建实例
  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()));
  }

  //计算总数
  long total = mongoTemplate.count(query, Student.class);

  //查询结果集
  List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
  Page<Student> studentPage = new PageImpl(studentList, pageable, total);
  return studentPage;
}

缺点:

不支持返回固定字段

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

  //动态拼接查询条件
  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());
  //计算总数
  long total = mongoTemplate.count(query, Student.class);

  //查询结果集条件
  BasicDBObject fieldsObject = new BasicDBObject();
  //id默认有值,可不指定
  fieldsObject.append("id", 1)  //1查询,返回数据中有值;0不查询,无值
        .append("name", 1);
  query = new BasicQuery(queryBuilder.get().toString(), fieldsObject.toJson());

  //查询结果集
  List<Student> studentList = mongoTemplate.find(query.with(pageable), Student.class);
  Page<Student> studentPage = new PageImpl(studentList, pageable, total);
  return studentPage;
} 

四、MongoTemplate结合Aggregation

  • 使用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;
  //获取满足添加的总页数
  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);

  //查询结果集
  Page<Student> studentPage = new PageImpl(results.getMappedResults(), pageable, totalCount);
  return studentPage;
}

以上就是JAVA代码实现MongoDB动态条件之分页查询的详细内容,更多关于JAVA 实现MongoDB分页查询的资料请关注脚本之家其它相关文章!

相关文章

  • java、spring、springboot中整合Redis的详细讲解

    java、spring、springboot中整合Redis的详细讲解

    这篇文章主要介绍了java、spring、springboot中整合Redis的详细讲解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • Java线程取消的三种方式

    Java线程取消的三种方式

    文章介绍了 Java 线程取消的 3 种方式,不推荐使用 stop 方法和 volatile 设标记位停止线程,线程中断机制是协作式的,一个线程请求中断,另一线程响应,线程可检查自身中断状态或捕获 InterruptedException 来合适处理以响应中断,确保安全有序停止,避免资源泄露等问题
    2024-12-12
  • 浅谈Spring与SpringMVC父子容器的关系与初始化

    浅谈Spring与SpringMVC父子容器的关系与初始化

    这篇文章主要介绍了浅谈Spring与SpringMVC父子容器的关系与初始化,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java中LinkedHashSet的底层机制详解

    Java中LinkedHashSet的底层机制详解

    这篇文章主要介绍了Java中LinkedHashSet的底层机制解读,   LinkedHashSet是具有可预知迭代顺序的Set接口的哈希表和链接列表实现,此实现与HashSet的不同之处在于,后者维护着一个运行于所有条目的双重链接列表,需要的朋友可以参考下
    2023-09-09
  • Java随机值设置(java.util.Random类或Math.random方法)

    Java随机值设置(java.util.Random类或Math.random方法)

    在编程中有时我们需要生成一些随机的字符串作为授权码、验证码等,以确保数据的安全性和唯一性,这篇文章主要给大家介绍了关于Java随机值设置的相关资料,主要用的是java.util.Random类或Math.random()方法,需要的朋友可以参考下
    2024-08-08
  • 详解Spring中Bean的作用域与生命周期

    详解Spring中Bean的作用域与生命周期

    Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的作用域与生命周期是非常必要的。这篇文章将问你详解一下Bean的作用域与生命周期,需要的可以参考一下
    2021-12-12
  • java求数组第二大元素示例

    java求数组第二大元素示例

    这篇文章主要介绍了java求数组第二大元素示例,需要的朋友可以参考下
    2014-04-04
  • Spring Security加密和匹配及原理解析

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

    我们开发时进行密码加密,可用的加密手段有很多,比如对称加密、非对称加密、信息摘要等,本篇文章给大家介绍Spring Security加密和匹配及原理解析,感兴趣的朋友一起看看吧
    2023-10-10
  • Java并发编程之创建线程

    Java并发编程之创建线程

    这篇文章主要介绍了Java并发编程中创建线程的方法,Java中如何创建线程,让线程去执行一个子任务,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • Java8的Lambda和排序

    Java8的Lambda和排序

    这篇文章主要介绍了Java8的Lambda和排序,对数组和集合进行排序是Java 8 lambda令人惊奇的一个应用,我们可以实现一个Comparators来实现各种排序,下面文章将有案例详细说明,想要了解得小伙伴可以参考一下
    2021-11-11

最新评论