Spring Boot Pagination
1 CommentLast Updated on May 7, 2021 by jt
Consider a scenario where a database query matches over 1000 records. You need to display the query results to users. In this scenario, you probably won’t want to display all records on a single page. Instead, you would want to display chunks of data of suitable sizes with high readability. To achieve this, you use pagination.
The, PaginationAndSortingRepository
interface which extends the CrudRepository
interface of Spring Data JPA provides this functionality (i.e. to retrieve the records using the pagination and sorting techniques).
If you are new to creating a simple Spring Boot application that uses CrudRepository
of Spring Data JPA, you can refer to one of my previous post on Spring Boot Web Application – Part 3 – Spring Data JPA
In this post, I will explain how to perform pagination in Spring Boot.
Dependency
We will create a Spring Boot REST API that communicates with an in-memory H2 database.
To get started, add the following dependencies to your pom.xml
file.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency>
Spring Boot Pagination Example
This is the code for Blog
entity class of the application.
Blog.java
package org.springframework.guru.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Blog { @GeneratedValue(strategy = GenerationType.AUTO) @Id private long blogId; private String blogTitle; public long getBlogId() { return blogId; } public String getBlogTitle() { return blogTitle; } public void setBlogId(long blogId) { this.blogId = blogId; } public void setBlogTitle(String blogTitle) { this.blogTitle = blogTitle; } }
In the preceding code, the @Entity
annotation specifies that the class is a JPA entity and is mapped to a database table.
The @Id
annotation specifies the primary key of the entity and the @GeneratedValue
sets the strategy that the database should use to generate the primary keys.
The BlogRepository
interface is this.
BlogRepository.java
package org.springframework.guru.repository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.guru.model.Blog; import org.springframework.stereotype.Repository; @Repository public interface BlogRepository extends PagingAndSortingRepository<Blog,Long> { }
The preceding repository interface is decorated with the @Repository
annotation. By extending from the Spring PagingAndSortingRepository
interface, the BlogRepository
interface inherits two methods to paginate data.
- Firstly, the
findAll(Pageable pageable)
method. This method accepts aPageable
object that represents pagination information. This method returns aPage
object meeting the pagination restriction provided in thePageable
object.Page
is a sublist of a list of objects. APage
object provides information about its position in the containing list. - Next, the
findAll(Sort sort)
method that accepts aSort
object that represents sorting options for queries. The method returns anIterable
of all entities sorted by the given options.
This is the code for the controller class.
BlogController.java
package org.springframework.guru.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.guru.model.Blog; import org.springframework.guru.repository.BlogRepository; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class BlogController { @Autowired private BlogRepository blogRepository; @GetMapping(value = "/blogPageable") Page blogPageable(Pageable pageable) { return blogRepository.findAll(pageable); } }
The preceding code creates a REST Controller that maps the request /blogPageable
to the method blogPageable()
. This method takes Pageable
as a parameter.
Note: For the purpose of this post, I have autowired the repository directly in the constructor. Ideally, we should have an intermediate service layer to handle the busin=ess requirements of the application.
For the embeded H2 database, specify its configuration in application.properties
.
application.properties
spring.datasource.url=jdbc:h2:mem:blogdb spring.datasource.driverClassName=org.h2.Driver spring.h2.console.enabled=true spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Testing Pagination
To test the pagination of data, we need to have some data present in H2.
One way to prefill the data into the database is by wring INSERT statements in the import.sql
file. Ensure that this file is under the resources folder of your project to be available on the classpath.
You can now build, package, and run the application.
This Figure shows the Blog table prefilled with data.
On the browser access the REST endpoint localhost:8090/blogPageable?size=2
. In this URL, note the size
path variable. It specifies the paging size to the application.
On sending the request, you will see the first two entries sent as response, as shown in this figure.
What if you want to sort the items according to one of its parameters?
Testing Sorting
To test the sorting of data, use the sort
path variable, like this.
localhost:8090/blogPageable?size=2&sort=blogTitle
The output of the query is this.
In the preceding output, note that the two blogs are sorted by the blog title in ascending order.
You can find the source code of this post on Github.
For in-depth knowledge of the Spring Framework and Spring Boot, you can check my Udemy Best Seller Course Spring Boot Microservices with Spring Cloud Beginner to Guru
Kinitopet
Great post! The examples on implementing pagination in Spring Boot were really helpful. I especially appreciated the clear explanations and code snippets. It’s nice to see how easily we can manage large datasets with pagination. Looking forward to more content like this!