Last updated: 2022-06-13
Pagination in a Spring Boot REST API
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. Best practices included.
Discover more
Spring Boot provides many features to support Pagination natively. However, the PageImpl
class is not directly usable with a RestTemplate
and also creates a lot of overhead when outputting via a REST API. Therefore in this article we would like to introduce a SimplePage
class that simplifies the JSON structure and can be used directly in a RestTemplate or TestRestTemplate.
Adding Pagination to the Application
To add pagination to a RestController we first need the input parameters. Using the Pageable class, the "page", "size" and "sort" parameters can be passed to the endpoint. These are automatically bound by Spring Boot into the object. Default values can be specified by adding annotations or adjusting certain application properties.
Example RestController with an endpoint supporting pagination
Since our repository extends JpaRepository
, we can pass our pageable object directly to the findAll()
method. The repository will return an object of type Page
containing the requested page and its content.
Our repository providing paged access by default
However, if we were to return Page
(or PageImpl
) directly through our endpoint, we would have the disadvantages described at the beginning. Therefore the intermediate service not only maps our entity to the DTO, but also returns the SimplePage class.
Example intermediate Service
The SimplePage class with full Jackson support
With our new class we simplify the JSON structure. It excludes unneeded properties from PageImpl
and overwrites the sort property so that it matches the input parameter as closely as possible.
The constructor is necessary so that Jackson can initialize the class from an input string. This adds support for serialization and deserialization, so that we can also call our endpoint using a RestTemplate.
The SimplePage class
The JSON output of our REST API will look like this. SimplePage
can be easily customized by expanding the constructor, for example if more fields are required.
JSON response of our new endpoint
Bootify helps you to create the first version of your next Spring Boot application including database schema and REST API. Pagination for the REST endpoints is available in the Professional plan, which also includes generation of basic test cases using Testcontainers.