Advertisement

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

阅读量:
776e71d35e8b5eb8b9f04cbf6ea57573.png

一、使用QueryByExampleExecutor

1. 继承MongoRepository

public interface StudentRepository extends MongoRepository {

}

2. 代码实现

采用例证配对机制-----仅允许针对字符串进行模糊搜索指令,并对其他类型执行精确匹配。

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");

Fillable pageable = PageRequest(studentReqVO.PageSize, studentReqVO.PageSize, 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添加一个筛选条件Criterias.where('createTime').lte(studentReqVO.getCreateTime());

向查询对象query添加一个筛选条件Criterias.where(' createTime ').lte(studentReqVO.getCreateTime());

}

//计算总数

long total = mongoTemplate.count(query, Student.class);

//查询结果集

创建学生列表studentLists = mongoTemplate.find(query.with(pageable), Student类);

Page studentPage = new PageImpl(studentList, pageable, total);

return studentPage;

}

实现二:使用Example和Criteria封装查询条件

public class Page {
public StudentRequestEntity[] getListWithExampleAndCriteria(StudentRequestEntity studentRequestEntity1, StudentRequestEntity studentRequestEntity2) {
// 方法体
}
}

Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

Pageable instance named pageable is created by calling the method PageRequest.of with three arguments: studentReqVO's page number, page size, and a sort operation.

Student student = new Student();

BeanUtils.copyProperties(studentReqVO, student);

//创建匹配器,即如何使用查询条件

ExampleMatcher matcher = ExampleMatcher.matching() //构建对象

.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // 通过指定 ExampleMatcher.StringMatcher.CONTAINING 来设置默认字符串匹配函数以调整默认的字符串匹配行为至模糊查询模式

.withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写

.通过与"name"使用示例匹配器的包含性检查来查询

.withIgnorePaths("pageNum", "pageSize"); //忽略属性,不参与查询

//创建实例

Example example = Example.of(student, matcher);

Query query = new Query(Criteria.byExample(example));

if (studentReqVO.getCreateTime() != null){

在查询中添加筛选条件,在使用where方法过滤中包含创建时间不大于等于学生请求对象获取的时间

}

//计算总数

long total = mongoTemplate.count(query, Student.class);

//查询结果集

const studentCollection = mongoTemplate.find(query.with(.pageable), studentsClass);

Page studentPage = new PageImpl(studentList, pageable, total);

return studentPage;

}

缺点:

不支持返回固定字段

三、MongoTemplate结合BasicQuery

BasicQuery是Query的子类

支持返回固定字段

public Page getListWithBasicQuery(StudentReqVO studentReqVO) {

Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

Pageable 实例 pageable = PageRequest.of(studentReqVO.get 页数(), studentReqVO.get 每页人数(), sort);

Pageable 实例 pageable = PageRequest.of(studentReqVO.get 页数(), studentReqVO.get 每页人数(), sort);

QueryBuilder queryBuilder = new QueryBuilder();

//动态拼接查询条件

if (!StringUtils.isEmpty(studentReqVO.getName())) {

Pattern pattern = Pattern.compile("(?:[\s]|\.)" + studentReqVO.getName() + "(?:[^\s]|\.)$", Pattern.CASE_INSENSITIVE);

queryBuilder.and("name").regex(pattern);

}

if (studentReqVO.getSex() != null) {

queryBuilder.and("sex").is(studentReqVO.getSex());

}

if (studentReqVO.getCreateTime() != null) {

在查询 builder 中同时设置(不大于)学生请求体中的获取时间字段;

}

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());

//查询结果集

ArrayList studentList = mongoTemplate.find(query.with(pageable), Student.class); 该代码通过MongoTemplate按照指定条件进行查询,并返回所有符合条件的学生数据

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");

pager pageable = new PageRequest(student_reqvo.getRequest_num(), student_reqvo.getRequest_page_size(), sort);

Integer pageNum = studentReqVO.getPageNum();

Integer pageSize = studentReqVO.getPageSize();

List operations = new ArrayList<>();

if (!StringUtils.isEmpty(studentReqVO.getName())) {

按照以下方式定义一个模式变量pattern:从字符串开始匹配到指定字段名称.*$进行案例-insensitive匹配。

Criteria criteria = Criteria.where("name").regex(pattern);

operations.add(Aggregation.match(criteria));

}

if (null != studentReqVO.getSex()) {

operations.insert(Aggregation.gather(Criteria.where("sex").is(studentReqVO.getSex())))

}

long totalCount = 0;

//获取满足添加的总页数

if (null != operations && operations.size() > 0) {

aggregationCount: new Aggregation(operations);
//当 operations 为空时会抛出错误

AggregationResults resultsCount = mongoTemplate.execute(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);

AggregationResultSet results = mongoTemplate.aggregate(aggregation, "student", Student.class);

//查询结果集

Page studentPage = new PageImpl(results.mappedResults(),页面,总计);

return studentPage;

}

这就是Java代码实现MongoDB基于动态条件的分页查询的具体操作流程。如需了解更多信息,请参考云海天教程的其他相关文章。

原文链接:https://www.cnblogs.com/wslook/p/9275861.html

全部评论 (0)

还没有任何评论哟~