2015-03-13 133 views
9

我有一个可分页查询:分页与mongoTemplate

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

如何我MongoTemplate执行呢?我没有看到一种方法返回Page<T>

回答

5

MongoTemplate没有方法返回Pagefind()方法返回普通的List

with(new PageRequests(page, size)用于内部调整skiplimit与MongoDB的查询(通过计数查询我想着手)

Page可以结合使用MongoDB repositories其是春天数据存储库的一个专门的情况。

因此,您必须使用MongoRepositoryPage findAll(Pageable pageable)作为分页结果(实际上从PagingAndSortingRepository继承)。

4

的确,MongoTemplate没有findXXX与Pageables。

但是,您可以使用Spring存储库PageableExecutionUtils

在您的例子就应该是这样的:

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

像原来春数据仓库中,PageableExecutionUtils会做计数请求,并将其包装成一个漂亮的Page你。

Here你可以看到春天是这样做的。

+0

其中是PageableExecutionUtils类? – 2017-10-16 06:44:58

+0

从Spring数据共享:https://github.com/spring-projects/spring-data-commons/blob/master/src/main/java/org/springframework/data/repository/support/PageableExecutionUtils.java – d0x 2017-10-16 10:10:46

+0

好的,谢谢。我用了一个老版本的弹簧。 – 2017-10-16 10:46:06

0

根据d0x的回答,看着spring code。我正在使用这种变体,它不依赖于spring-boot-starter-data-mongodb依赖关系,而无需添加弹簧数据共享。

@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; 
}