分页的时候出现页码和总页数不对应,困扰了蛮久,因此,特意记录下来
Query query = new Query();
//分页查询
long count = mongoTemplate.count(query, Map.class,collection_name); //总数量
Pageable pageable = PageRequest.of(0, 3); //第一页 ,每页三条记录
List<Map> list = mongoTemplate.find(query.with(pageable),Map.class, collection_name); //list数据集
PageImpl<Map> pageImpl = new PageImpl<Map>(list,pageable,count); //分页
MongoPage<Map> mongodbPage = MongoPage.getMongodbPage(pageImpl); //自定义封装分页信息,基本就是get PageImpl里面的信息
以上代码是可以正确分页的
说说我之前错误的地方,是这个count的问题,这个count要么新建一个Query ,要么在query.with(pageable)之前进行查询,否则查找的信息就是不对劲的
以下是错误示范:
Pageable pageable = PageRequest.of(0, 3); //第一页 ,每页三条记录
List<Map> list = mongoTemplate.find(query.with(pageable),Map.class, collection_name); //list数据集
//这里 query已经包含了分页PageRequest,因此count的数量是当前页面大小 也就是pageSize
long count = mongoTemplate.count(query, Map.class,collection_name); //总数量