当前位置:   article > 正文

mongodb java分页查询_JAVA代码实现MongoDB动态条件之分页查询

java不支持mongo分片的查询

776e71d35e8b5eb8b9f04cbf6ea57573.png

一、使用QueryByExampleExecutor

1. 继承MongoRepository

public interface StudentRepository extends MongoRepository {

}

2. 代码实现

使用ExampleMatcher匹配器-----只支持字符串的模糊查询,其他类型是完全匹配

Example封装实体类和匹配器

使用QueryByExampleExecutor接口中的findAll方法

public Page 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 example = Example.of(student, matcher);

Page students = studentRepository.findAll(example, pageable);

return students;

}

缺点:

不支持过滤条件分组。即不支持过滤条件用 or(或) 来连接,所有的过滤条件,都是简单一层的用 and(并且) 连接

不支持两个值的范围查询,如时间范围的查询

二、MongoTemplate结合Query

实现一:使用Criteria封装查询条件

public Pa

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55974
推荐阅读
相关标签
  

闽ICP备14008679号