Last updated: July 28, 2021
Pagination in a Spring Boot REST API
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. Desired default values can also be added by means of further annotations.
Example RestController with an endpoint supporting pagination
The default behaviour can also be configured with further application properties.
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
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, 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.