Enterprise Java

Pagination and Sorting with Spring Data JPA

Learn Pagination and Sorting with Spring Data JPA with code examples. Understand how to get Paginated and Sorted results using Springs PagingAndSortingRepository interface.

1 Overview

While dealing with large amount of data the lazy processing is often essential. Even if a service returns a huge amount of data the consumer is less likely using it. Consider a shopping website, where customer searches for a product and the website has thousands of products to display. Fetching thousands of products and displaying it on a web page will be very time consuming. In most of the cases the customer may not even look at all of the products.

For such cases a technique called as Pagination is used. Only a small subset of products (page) is displayed at first and customer can ask to see the next subset (page) and so on. This is called as Pagination.

Want to learn using Java Persistence API (JPA) with Spring and Spring Boot ?

Read this:

2 Entity

For the sake of this tutorial, we will consider the simplest example of ‘Employee‘ entity. Below is the Employee entity class.

@Entity
public class Employee {
    @Id private Long name;
 
    private String firstName;
    private String lastName;
    private Date dateOfBirth;
    private Integer age;
    private String designation;
    private double salary;
    private Date dateOfJoining;
 
    public Long getName() {
        return name;
    }
 
    public void setName(Long name) {
        this.name = name;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
 
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public String getDesignation() {
        return designation;
    }
 
    public void setDesignation(String designation) {
        this.designation = designation;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
 
    public Date getDateOfJoining() {
        return dateOfJoining;
    }
 
    public void setDateOfJoining(Date dateOfJoining) {
        this.dateOfJoining = dateOfJoining;
    }
}

3 Employee Repository

In article Spring Data JPA Query Methods, we have already learnt about Spring repository interfaces and query methods. Here, we have to learn Pagination, so we will use Spring’s PagingAndSortingRepository.

@Repository
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {
 
    Page<Employee> findAll(Pageable pageable);
 
    Page<Employee> findByFirstName(String firstName, Pageable pageable);
 
    Slice<Employee> findByFirstNameAndLastName(String firstName, String lastName, Pageable pageable);
}

4 Pagination

Have a look at the EmployeeRepository, the method accepts Pageable arguments. Pageable is an interface defined by Spring which holds a Page request. Let’s see how to create a Page Request.

Pageable pageable = PageRequest.of(0, 10);
Page<Employee> page = employeeRepository.findAll(pageable);

In the first line we created a Page request of 10 employees and asked for first (0) page. The page request the passed to findAll to get a Page of Employees as response.

If we want to access next set of subsequent pages we can increase the page number every time.

PageRequest.of(1, 10);
PageRequest.of(2, 10);
PageRequest.of(3, 10);
...

5 Sorting

The Spring Data JPA provides a Sort object in order to provide a sorting mechanism. Lets have a look at the ways of sorting.

employeeRepository.findAll(Sort.by("fistName"));
 
employeeRepository.findAll(Sort.by("fistName").ascending().and(Sort.by("lastName").descending());

Obviously, the first one simply sorts by ‘firstName’ and the other one sorts by ‘firstName’ ascending and ‘lastName’ descending.

Pagination and Sort together

Pageable pageable = PageRequest.of(0, 20, Sort.by("firstName"));
        
        
Pageable pageable = PageRequest.of(0, 20, Sort.by("fistName").ascending().and(Sort.by("lastName").descending());

6 Slice vs Page

In the EmployeeRepository we saw one of the method returns Slice and the other returns Page. Both of them are Spring Data JPA, where Page is a sub-interface of Slice. Both of them are used to hold and return a subset of data. Let’s have a look at them one by one

Slice

The Slice knows if it has content, if it is first or the last slice. It is also capable of returning Pageable used in the current and previous slices. Lets have a look at some important methods of Slice.

List<T> getContent(); // get content of the slice
 
Pageable getPageable(); // get current pageable
 
boolean hasContent(); 
 
boolean isFirst();
 
boolean isLast();
 
Pageable nextPageable(); // pageable of the next slice
 
Pageable previousPageable(); // pageable of the previous slice

Page

The Page is a sub-interface of Slice and has couple of additional methods. It knows the number of total pages in the table as well as total number of records. Below are some important methods from Page.

static <T> Page<T> empty; //create an empty page
 
long getTotalElements(); // number of total elements in the table
 
int totalPages() // number of total pages in the table

7 Summary

In this Pagination and Sorting with Spring Data JPA article we learnt why pagination is required. We learnt how to get paginated as well as sorted subsets of data. We have also seen the Slice and Page interfaces and their differences.

Published on Java Code Geeks with permission by Amit Phaltankar, partner at our JCG program. See the original article here: Pagination and Sorting with Spring Data JPA

Opinions expressed by Java Code Geeks contributors are their own.

Amit Phaltankar

Amit Phaltankar is a Technology enthusiast who has huge passion for sharing what he knows. Amit works as a Java Technology Lead and has huge experience in Programming, Unit Testing, OOAD, Functional Programming, Big Data Technologies, micro-services, and Databases.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anil Anshu
Anil Anshu
3 years ago

nice explanation!

Zhassulan Tokbayev
Zhassulan Tokbayev
1 year ago

It’s working very slow. Db pagination better to use.

Back to top button