How to add pagination to a Spring Boot app

featured_image

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:

  • the TimeTraveller entity with id and name properties,
  • TimeTravellerRepository,
  • TimeTravellerService for fetching data,
  • TimeTravellerController for providing the endpoint.

Requirements

The following fragment of the pom.xml file shows dependencies used in the project:

Enable pagination

To allow paginating requested data we have to make sure that TimeTravellerRepository extends the PagingAndSortingRepository interface:

Now the 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 TimeTravellerServiceTest:

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 for http://localhost:8080/api/timetravellers?page=0&size=5&sort=id,asc  will look like this:

 

Photo by Allef Vinicius on StockSnap

2 thoughts on “How to add pagination to a Spring Boot app

  1. Simply wish to say your article is as astounding. The clearness in your put up is just spectacular and i could think you are a professional on this subject. Well with your permission allow me to clutch your feed to stay up to date with impending post. Thanks a million and please carry on the rewarding work.

Leave a Reply to http://canadianorderpharmacy.com/ Cancel reply

Your email address will not be published. Required fields are marked *