The spring-cursor-pagination Java library allows to easily implement cursor pagination for Spring Boot projects.
This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal)
Spring-cursor-pagination is currently available only for mongodb. NEVER sort by fields that may contain null values to prevent unexpected results.
- First add the library to the list of your project dependencies.
<dependency>
<groupId>it.davidepedone</groupId>
<artifactId>spring-cursor-pagination-mongodb</artifactId>
<version>last-release-version</version>
</dependency>
- Optionally define a POJO class to map request filter
public class PostSearchFilter {
private String author;
// getter/setter
}
- Define a service class that extends
CursorPaginationService
in order to indicate entity class, a list of sortable field and customize query against database (filter and authz checks)
@Service
public class PostPaginationService extends CursorPaginationService<Post, PostSearchFilter> {
public PostPaginationService(MongoOperations mongoOperations) {
super(mongoOperations, List.of("createdAt", "author"), Post.class);
}
@Override
public void configSearchQuery(Query query, @Nullable PostSearchFilter filter, @Nullable Principal principal) {
Optional.ofNullable(filter).map(PostSearchFilter::getAuthor).ifPresent(a -> {
query.addCriteria(where("author").is(a));
});
}
}
- Update or create controller method and that's it
public class PostController {
@Autowired
private PostPaginationService postPaginationService;
@GetMapping
public CursorPaginationSlice<Post> getAll(PostSearchFilter postSearchFilter, CursorPageable pageRequest) {
return postPaginationService.executeQuery(pageRequest, postSearchFilter, null);
}
}
To change query string parameter names just define a CursorPageableHandlerMethodArgumentResolverCustomizer
bean:
@Bean
public CursorPageableHandlerMethodArgumentResolverCustomizer customizer() {
return c -> {
c.setContinuationTokenParameterName("ct");
c.setSizeParameterName("sz");
c.setMaxPageSize(20);
};
}
Check out a simple demo project here
The spring-cursor-pagination
libraries are hosted on maven central repository.
The artifacts can be accessed at the following locations:
Releases:
Snapshots: