Pagination with mongoTemplate

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

I have a Query with Pageable:

Query query = new Query().with(new PageRequests(page, size)) 

How can I execute it with MongoTemplate ? I don't see a single method returning Page<T>.

回答1:

MongoTemplate does not have methods to return Page. The find() methods return an ordinary List.

with(new PageRequests(page, size) is used internally to adjust skip and limit with a MongoDB query (proceeded by a count query I think)

Page can be used in conjunction with MongoDB repositories which is a specialized case of Spring data repositories.

Thus, you'll have to use MongoRepository's Page findAll(Pageable pageable) for paginated results (actually inherited from PagingAndSortingRepository).



回答2:

It's true that the MongoTemplate doesn't have findXXX with Pageables.

But you can use the Spring Repository PageableExecutionUtils for that.

In your example it would look like this:

Pageable pageable = new PageRequests(page, size); Query query = new Query().with(pageable); List<XXX> list = mongoTemplate.find(query, XXX.class); return PageableExecutionUtils.getPage(                        list,                         pageable,                         () -> mongoTemplate.count(query, XXX.class)); 

Like in the original Spring Data Repository, the PageableExecutionUtils will do a count request and wrap it into a nice Page for you.

Here you can see that spring is doing the same.



回答3:

Based on d0x's answer and looking at the spring code. I'm using this variation which works off the spring-boot-starter-data-mongodb dependency without needing to add spring data commons.

@Autowired private MongoOperations mongoOperations;  @Override public Page<YourObjectType> searchCustom(Pageable pageable) {     Query query = new Query().with(pageable);     // Build your query here      List<YourObjectType> list = mongoOperations.find(query, YourObjectType.class);     long count = mongoOperations.count(query, YourObjectType.class);     Page<YourObjectType> resultPage = new PageImpl<YourObjectType>(list , pageable, count);     return resultPage; } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!