Pagination and Sorting using Spring Data JPA

1. Overview

Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks.

Also, we often need to sort that data by some criteria while paging.

In this tutorial, we’ll learn how to easily paginate and sort using Spring Data JPA.

2. Initial Setup

First, let’s say we have a Product entity as our domain class:

@Entity 
public class Product {
    
    @Id
    private long id;
    private String name;
    private double price; 

    // constructors, getters and setters 

}

Each of our Product instances has a unique identifier: id, its name and its price associated with it.

3. Creating a Repository

To access our Products, we’ll need a ProductRepository:

public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

    List<Product> findAllByPrice(double price, Pageable pageable);
}

By having it extend PagingAndSortingRepository, we get findAll(Pageable pageable) and findAll(Sort sort) methods for paging and sorting.

Conversely, we could have chosen to extend JpaRepository instead, as it extends PagingAndSortingRepository too.

Once we extend PagingAndSortingRepositorywe can add our own methods that take Pageable and Sort as parameters, like we did here with findAllByPrice.

Let’s take a look at how to paginate our Products using our new method.

4. Pagination

Once we have our repository extending from PagingAndSortingRepository, we just need to:

  1. Create or obtain a PageRequest object, which is an implementation of the Pageable interface
  2. Pass the PageRequest object as an argument to the repository method we intend to use

We can create a PageRequest object by passing in the requested page number and the page size.

Here the page count starts at zero:

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

Pageable secondPageWithFiveElements = PageRequest.of(1, 5);

In Spring MVC, we can also choose to obtain the Pageable instance in our controller using Spring Data Web Support.

Once we have our PageRequest object, we can pass it in while invoking our repository’s method:

Page<Product> allProducts = productRepository.findAll(firstPageWithTwoElements);

List<Product> allTenDollarProducts = 
  productRepository.findAllByPrice(10, secondPageWithFiveElements);

The findAll(Pageable pageable) method by default returns a Page<T> object.

However, we can choose to return either a Page<T>, a Slice<T>, or a List<T> from any of our custom methods returning paginated data.

Page<T> instance, in addition to having the list of Products, also knows about the total number of available pages. It triggers an additional count query to achieve it. To avoid such an overhead cost, we can instead return a Slice<T> or a List<T>.

Slice only knows whether the next slice is available or not.

5. Pagination and Sorting

Similarly, to just have our query results sorted, we can simply pass an instance of Sort to the method:

Page<Product> allProductsSortedByName = productRepository.findAll(Sort.by("name"));

However, what if we want to both sort and page our data?

We can do that by passing the sorting details into our PageRequest object itself:

Pageable sortedByName = 
  PageRequest.of(0, 3, Sort.by("name"));

Pageable sortedByPriceDesc = 
  PageRequest.of(0, 3, Sort.by("price").descending());

Pageable sortedByPriceDescNameAsc = 
  PageRequest.of(0, 5, Sort.by("price").descending().and(Sort.by("name")));

Based on our sorting requirements, we can specify the sort fields and the sort direction while creating our PageRequest instance.

As usual, we can then pass this Pageable type instance to the repository’s method.

6. Conclusion

In this article, we learned how to paginate and sort our query results in Spring Data JPA.

As always, the complete code examples used in this article are available over on Github.

Related posts:

REST Web service: Basic Authentication trong Jersey 2.x
Java Program to Describe the Representation of Graph using Incidence List
Quick Guide to Spring Bean Scopes
Java Program to Implement Word Wrap Problem
Serve Static Resources with Spring
JPA/Hibernate Persistence Context
Java Program to Implement Park-Miller Random Number Generation Algorithm
Comparing Objects in Java
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Java Program to Implement Strassen Algorithm
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
How to Manually Authenticate User with Spring Security
Java Program to Implement Shoelace Algorithm
Java 8 Collectors toMap
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Getting Started with Stream Processing with Spring Cloud Data Flow
Java toString() Method
Bootstrapping Hibernate 5 with Spring
Immutable ArrayList in Java
Spring AMQP in Reactive Applications
The HttpMediaTypeNotAcceptableException in Spring MVC
Chuyển đổi Array sang ArrayList và ngược lại
Jackson – Change Name of Field
Java Program to Implement the RSA Algorithm
Java InputStream to String
Java Program to Implement Quick sort
Constructor Injection in Spring with Lombok
Java Program to Find the Nearest Neighbor Using K-D Tree Search
Java TreeMap vs HashMap
Mockito and JUnit 5 – Using ExtendWith