mongorepository查询条件_MongoDB动态条件之分页查询
一、使用QueryByExampleExecutor
1. 继承MongoRepositorypublic 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 Page 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 studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page studentPage = new PageImpl(studentList, pageable, total);
return studentPage;
}
实现二:使用Example和Criteria封装查询条件
public Page 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 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 studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page studentPage = new PageImpl(studentList, pageable, total);
return studentPage;
}
缺点:不支持返回固定字段
三、MongoTemplate结合BasicQueryBasicQuery是Query的子类
支持返回固定字段
public Page 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 studentList = mongoTemplate.find(query.with(pageable), Student.class);
Page studentPage = new PageImpl(studentList, pageable, total);
return studentPage;
}
四、MongoTemplate结合Aggregation使用Aggregation聚合查询
支持返回固定字段
支持分组计算总数、求和、平均值、最大值、最小值等等
public Page 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 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 resultsCount = mongoTemplate.aggregate(aggregationCount, "student", Student.class);
totalCount = resultsCount.getMappedResults().size();
} else {
List 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 results = mongoTemplate.aggregate(aggregation, "student", Student.class);
//查询结果集
Page studentPage = new PageImpl(results.getMappedResults(), pageable, totalCount);
return studentPage;
}
mongorepository查询条件_MongoDB动态条件之分页查询相关推荐
- sql查询 关联帖子_MySQL的大分页查询该如何优化?
点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 转自公众号:yangyidba 一 背景 大部分开发和DBA同行都对分页查询非常非常了解,看帖子翻页需 ...
- Java使用MongoTemplate实现多条件、模糊查询、排序、范围、分页查询
场景: 查询客户列表, 不同条件之间取交集(且的关系), 单个条件内取并集(或的关系) 实现细节如下: 1. 全等于 (手机号全字匹配) 2. 模糊查询 (客户名称模糊搜索) 3. 单个条件查询多个字 ...
- c3p0 参数 模糊查询_mybatis之动态sql,模糊查询,结果集处理,mybatis分页及特殊字符处理...
目标及项目目录结构 目标 1.mybatis动态sql 2.模糊查询 3.查询返回结果集的处理 4.分页查询 5.特殊字符处理 项目的目录结构 1.mybatis动态sql If.trim.forea ...
- php水平分表之后怎么查询,ThinkPHP5水平分表后分页查询解决方案
ThinkPHP5内置了partition方法,可用于实现简单的分表.新增,修改,删除,查询单条数据时,用partition方法都可以轻松搞定,因为这些操作有一个共同的特点,就是能事先明确的知道,我要 ...
- Mybatis:Example类的使用--基本增删改查,模糊查询,排序,or,分页查询
MyBatis Generator 介绍 MyBatis Generator:简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类 ...
- MySql实现分页查询的SQL,mysql实现分页查询的sql语句 (转)
摘要:MySQL数据库实现分页查询的SQL语句写法! 一:分页需求: 客户端通过传递start(页码),limit(每页显示的条数)两个参数去分页查询数据库表中的数据,那我们知道MySql数据库提供了 ...
- mybatis mysql 分页sql语句_MySql实现分页查询的SQL,mysql实现分页查询的sql语句(转)...
http://blog.csdn.net/sxdtzhaoxinguo/article/details/51481430 摘要:MySQL数据库实现分页查询的SQL语句写法! 一:分页需求: 客户端通 ...
- 递归函数c语言结束条件,满足动态条件时退出递归函数
使用函数生成汉明距离t内的所有位序列: void magic(char* str, int i, int changesLeft) { if (changesLeft == 0) { printf(& ...
- jpa mysql sql分页查询语句_jpa 中 Query 的分页查询和更新
1,查询分页 注意这个地方nativeQuery=true 代表的是可执行原生sql 先查询出来所有的数据,然后再差个总条数 返回page @Query(nativeQuery = true, val ...
最新文章
- redis-集群分片
- vim的配置管理和部署
- sscom 中文显示 乱码_解决SSM框架使用过程中的中文乱码问题
- SpringBoot的email发送ssl协议格式
- Raect Router 4 的使用 (1)
- 手机厂商探路互联网:硬件高利润时代已成历史
- python实验报告_20193102 实验一 《python程序设计》实验报告
- webstorm 主题导入方法
- AutoJs 4.1.1 实战教程
- WDM驱动和NT式驱动
- django之admin调整页面展示
- Qt我的文档 桌面路径
- Python保龄球计分Demo
- 微信小游戏声明文件(d.ts)
- Pathon简介和优势
- Extracting Multiple-Relations in One-Pass with Pre-Trained Transformers [论文研读]
- MyBatisPlus自动填充
- 小米电视怎么看cctv?安装小鲸电视免广告教程值得看
- Linux 压缩文件与命令
- 多媒体计算机技术论文结束语,多媒体计算机技术教学论文
热门文章
- 计算机二级word保存要不要加.docx,计算机二级word实操题.docx
- 图片质量低怎么办?这个网站很不错!
- 你之所以没成为成就,就是因为太刻苦了!
- GraPhlAn绘制的超高颜值物种树Cladogram
- 易生信高级转录组分析和数据可视化-最后一天报名
- NAR:UNITE真菌鉴定ITS数据库——处理未分类和并行分类(数据库文章阅读模板)
- 斯坦福大学统计系教授带你玩转微生物组分析
- 你想要的生物信息知识全在这——生信宝典文章目录
- R语言构建xgboost模型:使用xgb.DMatrix保存、加载数据集、使用getinfo函数抽取xgb.DMatrix结构中的数据
- seaborn使用FacetGrid函数可视化山脊图(Ridgeline Plot with Seaborn)