使用Spring数据和分页遍历所有结果

时间:2019-01-10 15:18:55

标签: spring spring-data

我正在呼叫分页服务 我可以使用以下代码遍历所有分页集合:

Pageable pageable = PageRequest.of(0,100);
Page<Event> events = eventsService.getEventsPage(pageable);
while(!events.isLast()) {
    doStuff(events)
    events = eventsService.getEventsPage(events.nextPageable())
}
doStuff(events) // rest of events

有没有更优雅的解决方案?我需要分页,因为否则,系统将耗尽内存。

2 个答案:

答案 0 :(得分:0)

我会使用Slice(由Page继承的getContent()

  

List <T> getContent()

     

将页面内容返回为List

Pageable pageable = PageRequest.of(0,100);
Page<Event> events = eventsService.getEventsPage(pageable);
List<Event> eventList = events.getContent();
for (Event event : eventList) {
    // do stuff 
}

答案 1 :(得分:0)

我觉得不得不陈述两次服务电话和doStuff有点脆弱。您可以利用以下事实:如果当前页面已经是最后一页,则nextPageable()将为您提供unpaged单身。

Pageable pageable = PageRequest.of(0,100);
do {
    Page<Event> events = eventsService.getEventsPage(pageable);
    doStuff(events)
    pageable = events.nextPageable();
} while(pageable.isPaged())

这里是nextPageable()的文档。

 /**
 * Returns the {@link Pageable} to request the next {@link Slice}. Can be {@link Pageable#unpaged()} in case the
 * current {@link Slice} is already the last one. Clients should check {@link #hasNext()} before calling this method.
 *
 * @return
 * @see #nextOrLastPageable()
 */
Pageable nextPageable();