用mongoTemplate分页
我有一个可查询的查询:
Query query = new Query().with(new PageRequests(page, size))
如何使用MongoTemplate执行它? 我没有看到返回Page
的单个方法。
MongoTemplate
没有返回Page
方法。 find()
方法返回一个普通的List
。
with(new PageRequests(page, size)
在内部用于调整MongoDB查询的skip
和limit
(我认为是计数查询)
Page
可以与MongoDB存储库一起使用,这是Spring数据存储库的一个特例。
因此,您必须使用MongoRepository
的Page findAll(Pageable pageable)
作为分页结果(实际上是从PagingAndSortingRepository
inheritance的)。
确实, MongoTemplate
没有带有Pageables的findXXX
。
但是您可以使用Spring Repository PageableExecutionUtils
。
在您的示例中,它看起来像这样:
Pageable pageable = new PageRequests(page, size); Query query = new Query().with(pageable); List list = mongoTemplate.find(query, XXX.class); return PageableExecutionUtils.getPage( list, pageable, () -> mongoTemplate.count(query, XXX.class));
与最初的Spring Data Repository一样, PageableExecutionUtils
将执行计数请求并将其包装到一个漂亮的Page
中。
在这里你可以看到spring也在做同样的事情。
根据d0x的答案并查看弹簧代码 。 我正在使用这种变体,它可以解决spring-boot-starter-data-mongodb依赖关系,而无需添加spring数据公共。
@Autowired private MongoOperations mongoOperations; @Override public Page searchCustom(Pageable pageable) { Query query = new Query().with(pageable); // Build your query here List list = mongoOperations.find(query, YourObjectType.class); long count = mongoOperations.count(query, YourObjectType.class); Page resultPage = new PageImpl (list , pageable, count); return resultPage; }