Providing pagination for displaying large set of data will improve user experience and reduce the response time. Spring Boot comes with out-of-the-box solution for handling pagination, so let’s check how to implement it in an example application.
What we are going to build
In our example API we want to fetch time travellers on the
"/api/timetravellers" endpoint, but because the list can be elongated, we need to paginate the results.
We are working with:
TimeTravellerServicefor fetching data,
TimeTravellerControllerfor providing the endpoint.
The following fragment of the
pom.xml file shows dependencies used in the project:
To allow paginating requested data we have to make sure that
TimeTravellerRepository extends the PagingAndSortingRepository interface:
TimeTravellerService method can accept
Pageable instance as an argument and simply pass it when calling
findAll() method on the repository:
Check out the simple example test for this functionality in
Get paginated results
We are going to handle the following request:
The controller endpoint looks straightforward:
And below you can find the complementary test for the controller endpoint:
After you had the time traveller created in your API, the Postman output forwill look like this: