JAVA代码实现MongoDB动态条件之分页查询
作者:时间-海 发布时间:2022-05-21 12:44:11
标签: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;
}
来源:https://www.cnblogs.com/wslook/p/9275861.html


猜你喜欢
- 使用jni进行opencv开发可以快速地将PC端的opencv代码移植到手机上,但是如何在android studio下进行配置,网上几乎找
- 在谈 JVM 内存区域划分之前,我们先来看一下 Java 程序的具体执行过程,我画了一幅图。Java 源代码文件经过编译器编译后生成字节码文
- 本次数据请求使用postman, postman下载地址:https://www.getpostman.com/一、页面跳转1. 页面跳转@
- 从Java 5开始,Java语言对方法参数支持一种新写法,叫 可变长度参数列表,其语法就是类型后跟...,表示此处接受的参数为0到多个Obj
- 比如要获取打开摄像头的应用程序名称,只需要在frameworks/base/core/android/hardware/Camera.jav
- 前言直接使用项目或直接复制libs中的so库到项目中即可(当前只构建了armeabi),需要其他ABI可检下项目另外使用CMake构建即可。
- Android自带的SeekBar是水平的,要垂直的,必须自己写一个类,继承SeekBar。一个简单的垂直SeekBar的例子:(但是它其实
- 目录卡顿原理卡顿监控ANR原理卡顿原理主线程有耗时操作会导致卡顿,卡顿超过阀值,触发ANR。 应用进程启动时候,Zygote会反射调用Act
- 我在Eclipse/MyEclipse环境下都测试过了,都好使。需要2个组件,分别是: ext-4.0.2a.jsb2 spke
- 前言最近遇到了这样一个工作场景,需要写一批dubbo接口,再将dubbo接口注册到网关中,但是当dubbo接口异常的时候会给前端返回非常不友
- 本文以新建的CUDA的.cu程序来进行说明,同样也适用于C程序。一,发现问题1,首先我们在vs2019中创建了工程以后(我所创建的工程名称为
- Eureka注册的服务之间互相调用1.请求方启动类添加注解,扫描Eureka 中的全部服务@SpringBootApplication@En
- GitHub有一个开源控件PickerView,可以实现 * 联动的效果。虽然该控件使用非常简单,但是填充数据异常繁琐。GitHub上的Dem
- 简介:本文将帮助您使用 Spring Boot 创建简单的 REST 服务。你将学习什么是 REST 服务?如何使用 Spring Init
- Tab与TabHost:这就是Tab,而盛放Tab的容器就是TabHost 。如何实现?? 每一个Tab还对应了一个布局,这个就有点好玩了。
- 一、定义委托delegate void StudentDelegate();//【1】定义一个委托二、定义一个调用和定义事件的类/// &l
- 背景数据库在保存数据时,对于某些敏感数据需要脱敏或者加密处理,如果一个一个的去加显然工作量大而且容易出错,这个时候可以考虑使用 * ,本文针
- 微信聊天窗口的信息效果类似iphone上的短信效果,以气泡的形式展现,在Android上,实现这种效果主要用到ListView和BaseAd
- 本文详细总结了Android编程开发之性能优化技巧。分享给大家供大家参考,具体如下:1.http用gzip压缩,设置连接超时时间和响应超时时
- 断断续续的总算的把android开发和逆向