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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Trending

  • Accelerating AI Inference With TensorRT
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  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 user avatar
Amit Phaltankar
·
Feb. 20, 19 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
185.1K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!