Pagination with Spring Data

Last update: 26 November, 2017

Pagination is a common requirement in web applications where you need to show a large number of items on a page, but you don’t want to overwhelm the user with too much data. In this article, we’ll see how to use Spring Data’s built-in pagination support to easily implement pagination in your Spring Boot application.

Setting up the project

To get started, we’ll create a simple Spring Boot project using the Spring Initializr. Add the following dependencies to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
</dependency>

Next, create an entity class and a repository interface. For this example, we’ll use a simple Book entity with a title and an author:

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    // getters and setters
}

public interface BookRepository extends JpaRepository<Book, Long> {
}

Implementing pagination

With Spring Data, implementing pagination is as easy as adding a Pageable parameter to your repository method. For example, let’s say we want to retrieve a page of books sorted by title:

@GetMapping("/books")
public ResponseEntity<Page<Book>> getBooks(Pageable pageable) {
    Page<Book> page = bookRepository.findAll(pageable);
    return ResponseEntity.ok(page);
}

By default, Spring Data will return a maximum of 20 items per page. You can change this by setting the spring.data.web.pageable.default-page-size property in your application.properties file.

Testing pagination

To test our pagination endpoint, we can use the following curl command:

curl -i 'http://localhost:8080/books?page=0&size=10&sort=title,asc'

This will return the first page of books, with 10 items per page, sorted by title in ascending order.

Conclusion

In this article, we saw how easy it is to implement pagination with Spring Data in your Spring Boot application. Spring Data provides a powerful and flexible way to work with data, and pagination is just one of the many features it offers.

Contact

Sound like a fit?

Write me to learn more about my services and how we can work to create something similar and exceptional.

Drop me an email