赞
踩

一、使用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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。