Lately, I've been working on a project that requires cursor pagination, rather than traditional offset pagination. I find it confusing why there is no support for this in the framework itself. It can be done, but with a bit of a hack.
// Service
public List<Entity> search(int limit, Optional<Long> idCursor) {
// Kind of a hack to get the 'first' page, while actually offsetting the page with the 'idCursor'
var pageable = Pagerequest.of(0, limit);
return repository(pageable, idCursor)
}
// Repository
@Query("""
SELECT e from Entity e
WHERE (:idCursor is null or e.id > :idCursor)
ORDER BY e.id ASC
""")
List<Entity> search(Pageable pageable, Optional<Long> idCursor);
Cursor pagination is useful for searching a dataset that is constantly being updated. In this case, using offset pagination can result in incorrect data. This is because offsets can skip rows that were shifted by changes in the dataset.
Comment From: bclozel
Thanks for this report @cassis163
Good news this is already supported in recent Spring Data releases for several types of data stores. See https://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories.special-parameters