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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Trending

  • DZone's Article Submission Guidelines
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Integration Isn’t a Task — It’s an Architectural Discipline
  1. DZone
  2. Data Engineering
  3. Data
  4. Spring Data (Part 5): Paging and Sorting

Spring Data (Part 5): Paging and Sorting

Learn how to set up pagination with Spring Data so you can organize and sort your information to your liking.

By 
Shamik Mitra user avatar
Shamik Mitra
·
Oct. 14, 16 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
175.3K Views

Join the DZone community and get the full member experience.

Join For Free

When we perform bulk operations, like finding all instances of a "Person" from the database or finding everyone based on a country, we often do the paging so that we can present a small data chunk to the end user and, in the next request, we fetch the next data chunk. By doing this, we see two main advantages.

Advantages

This method enhances readability for end users. If we show everything on a page, then it will be long enough to need a scrollbar. The users will need to scroll to find a particular person, which is bad UI design.

It also reduces the query time and enhances performance as, in spite of fetching all the data, we only fetch a small chunk of data — amounting to less query time. A lot of UI technology supports client-side paging, which fetches all the data, and, based on the request, shows paginated data. But that doesn't reduce the query time, it only provides the first advantage.

Disadvantages

To request every data chunk, a server trip is required. You can optimize it through caching, but when an end user is in the process of fetching data, another Person can be added to the system. If that situation, it might show as the last entry of one page and the first entry of another.

But we are always using paging to fetch a small chunk of data, rather than all of it.

Spring Data and Pagination

Spring Data provides support for pagination. It creates all the logic to implement paging, like a count for the rows for all the pages and more.

Implementing paging is very easy in Spring Data. We just need to follow the steps below:

  1. In your custom repository, extend PagingAndSortingRepository.

  2. Create a PageRequest object, which is an implementation of the Pageable interface
    This PageRequest object takes the page number, the page size, and sorts direction and sort field.

  3. By passing the requested page number and page limit you can get the data for this page.
    If you pass the wrong page number, Spring Data will take care of that and not return any data.

Paging Code Implementation

1. Create a repository that extends PagingAndSortingRepository.

package com.example.repo;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import com.example.person.Person;

@Repository
public interface PersonRepositary extends PagingAndSortingRepository<Person, Long>,QueryDslPredicateExecutor<Person> {

    @Query("select p from Person p where p.country like ?1 order by country")
    List<Person> findByCountryContains(String country);

    List<Person> findPersonByHobbyName(String name);

    @Query("select p from Person p where p.id = ?1 and  country='America'")
    Person findOne(Long id);

}


2. Create domain objects.

package com.example.person;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;
    private String country;
    private String gender;

@OneToMany(mappedBy="person",targetEntity=Hobby.class,
       fetch=FetchType.EAGER,cascade=CascadeType.ALL)
        List<Hobby> hobby;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public String getGender() {
    return gender;
}
public void setGender(String gender) {
    this.gender = gender;
}

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}

public List<Hobby> getHobby() {
    return hobby;
}
public void setHobby(List<Hobby> hobby) {
    this.hobby = hobby;
}

public void addHobby(Hobby ihobby)
{
    if(hobby == null)
    {
        hobby = new ArrayList<Hobby>();
    }
    hobby.add(ihobby);
}
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", country=" + country + ", gender=" + gender + "]";
    }
}


3. Fetch all Persons. Create a PageRequest Object with a limit of 1 and requesting the first page.

package com.example.person;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.repo.HobbyRepository;
import com.example.repo.PersonRepositary;
import com.querydsl.core.types.dsl.BooleanExpression;


@SpringBootApplication
@EnableJpaRepositories("com.example.repo")
public class PersonApplication {

    @Autowired
    HobbyRepository hRepo;
    private static final Logger log = LoggerFactory.getLogger(PersonApplication.class);

    @Bean
    public CommandLineRunner demo(PersonRepositary repository) {
        findAll(repository);
        return null;
    }

    private PageRequest gotoPage(int page)
    {
        PageRequest request = new PageRequest(page,1)
        return request;
    }

    private void findAll(PersonRepositary repository)
    {

        Iterable<Person> pList = repository.findAll(gotoPage(0));
        for(Person p : pList)
        log.info("Person " + p);
    }


    public static void main(String[] args) {

        SpringApplication.run(PersonApplication.class, args);

    }
}


Output

Hibernate: 
    select
        count(person0_.id) as col_0_0_ 
    from
        person person0_
Hibernate: 
    select
        person0_.id as id1_1_,
        person0_.country as country2_1_,
        person0_.gender as gender3_1_,
        person0_.name as name4_1_ 
    from
        person person0_ limit ?

Person Person [id=13, name=Samir mitra, country=America, gender=male]


Paging and Sorting Code Implementation

To do the sorting, we have to pass the sort direction and sorting fields along with the page number and limit. Suppose we want to sort by country name in ascending order — we modify the goto method like so:

private PageRequest gotoPage(int page)
{
    PageRequest request = new PageRequest(page,1,Sort.Direction.ASC,"country");
    return request;
}


Output

 select
        count(person0_.id) as col_0_0_ 
    from
        person person0_
Hibernate: 
    select
        person0_.id as id1_1_,
        person0_.country as country2_1_,
        person0_.gender as gender3_1_,
        person0_.name as name4_1_ 
    from
        person person0_ 
    order by
        person0_.country asc limit ?

Here we pass the ascending order and country property. And there you have it! This should help you get your data sorted and organized just how you want it.

Data (computing) Spring Data Spring Framework Sorting

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Partner Resources

×

Comments

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: