In this short tutorial , we’ll see how easy it is to set up Pagination in a Spring Boot app .
Setup
We use Spring Boot 1.3.3.RELEASE , with MySQL as the Database and Spring Data JPA abstraction to work with MySQL. Indeed ,it is the Spring Data JPA module that makes it so easy to set up Pagination in a Spring boot app in the first place.
Scenario
We expose an endpoint /persons
. It will return a List of persons and other paging info(which we would see in a minute) based on the page
and size
parameters that were passed along with it.
For instance , /persons?page=0&size=3
would return a batch of the first 3 persons from the database
/persons?page=1&size=3
would return the next batch .
To begin with, we create a domain Person
class .
This is how our Controller looks like .
Notice that we haven’t passed RequestParams to our handler method .
When the endpoint /persons?page=0&size=3
is hit, Spring would automatically resolve the page
and size
parameters and create a Pageable
instance .
We would then pass this Pageable
instance to the Service layer ,which would pass it to our Repository layer .
Next,we create a PersonRepository
class to interact with the database.
The PersonRepository class is just an interface. This might be weird for those coming from traditional Spring MVC world wherein you had to write implementation classes , and interacted with the database using Hibernate. Well, you don’t need to do that anymore. The PagingAndSortingRepository extends the CrudRepository , thereby adding Paging capabilities .
Now all we need to do is to create a PersonService
interface and PersonServiceImpl
to expose the repository.
This is all, really ! Let’s test it out . I created a test class to insert a batch of 20 Person objects . You can do this manually ofcourse.
Great,we’re all done . Let’s hit the endpoint with Postman .
The snapshot doesn’t display the entire JSON. So here it is .
You can download the sample here