DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Trending

  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern
  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers
  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big
  • Why Kotlin or Java Is the Wrong Question For Enterprises

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Pagination and Sorting With Spring Data JPA

Pagination and Sorting With Spring Data JPA

Learn how to implement pagination and sorting with the Spring Data JPA.

By 
Amit Phaltankar
·
Feb. 20, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
186.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Overview

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

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

To learn the basics of JPA and Spring Data JPA, check out these links:

  • Hands-on Spring Data JPA (A Spring Data JPA Learning Series)
  • What is JPA, Spring Data and Spring Data JPA

Entity

For the sake of this tutorial, we will consider the simplest example of the 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;
    }
}


Want to learn more about using the Java Persistence API (JPA) with Spring and Spring Boot?
Check out these additional links:

  • Spring Boot with Spring Data JPA
  • Spring Data JPA Composite Key with @EmbeddedId
  • Spring Data JPA find by @EmbeddedId Partially
  • Java Persistence API Guide
  • Spring Data JPA Query Methods

Employee Repository

In the article Spring Data JPA Query Methods, we have already learned about Spring repository interfaces and query methods. Here, we need 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);
}


Pagination

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

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



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

If we want to access the 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);
...


Sorting

Spring Data JPA provides a Sort object in order to provide a sorting mechanism. Let's 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());


Slice Vs. Page

In theEmployeeRepository, we saw one of the methods returns Slice and the other return 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 and if it is the first or last slice. It is also capable of returning the Pageableused in the current and previous slices. Let's 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

 Page is a sub-interface of Slice and has a couple of additional methods. It knows the number of total pages in the table as well as the 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


Summary

In this pagination and sorting example with Spring Data JPA, we learned why pagination is required. We also learned how to get paginated as well as sorted subsets of data. Lastly, we have also seen the Slice and Page interfaces and their differences.

Read the original post Pagination and Sorting with Spring Data JPA here.

Spring Framework Spring Data Data (computing) Sorting Database

Published at DZone with permission of Amit Phaltankar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • The Generic Way To Convert Between Java and PostgreSQL Enums

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook