Pagination And Sorting With Spring Data JPA

Posted By : Himanshu Kumar | 29-Sep-2018

Introduction :-

 

When we perform mass activities, such as discovering all "Person"s from the database or discovering everybody in light of a nation, we regularly do the paging with the goal that we can display a little information lump to the end client and, in the following solicitation, we get the following information piece. By doing this, we see two primary points of interest.

 

Advantages -

 

This strategy improves clarity for end clients. In the event that we demonstrate everything on a page, at that point it will be sufficiently long to require a scrollbar. The clients should look to locate a specific individual, which is awful UI outline.

 

It likewise decreases the question time and upgrades execution as, disregarding getting every one of the information, we just get a little piece of information — adding up to less inquiry time. A great deal of UI innovation bolsters customer side paging, which brings every one of the information, and, in light of the demand, indicates paginated information. In any case, that doesn't decrease the question time, it just gives the primary favorable position.

 

Disadvantages :-

 

To ask for each datum piece, a server trip is required. You can improve it through storing, however when an end client is getting information, someone else can be added to the framework. In the event that that circumstance, it may appear as the last passage of one page and the primary section of another.

 

Yet, we are continually utilizing paging to bring a little piece of information, as opposed to every last bit of it.

 

Spring Data and Pagination: -

 

Spring Data offers help for pagination. It makes all the rationale to execute paging, similar to a mean the columns for every one of the pages.

 

Executing paging is simple in Spring Data. We simply need to take after the means beneath:

 

In your custom vault, expand PagingAndSortingRepository.

 

Make a PageRequest question, which is an execution of the Pageable interface

 

This PageRequest question takes the page number, the page size, and sorts heading and sort field.

 

By passing asked for page number and page restrain you can get the information for this page.

 

On the off chance that you pass a wrong page number Spring information will deal with that and not restore any information.

 

Steps to Implement pagination in spring boot  :-

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 entity class for model :-


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

 

Implementation of paging and sorting with spring data jpa :-

 

For sorting, we have to pass the sort direction and fields by which we want get data 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.

About Author

Author Image
Himanshu Kumar

Himanshu Kumar is a seasoned Backend Developer with extensive experience in the industry. He has a deep understanding and hands-on expertise in a range of technologies, including Core Java, Spring-Boot, Hibernate, Apache Kafka messaging queue, and blockchain development with Ethereum, Tron, and smart contract development. He is also well-versed in relational databases like MySQL and PostgreSQL. His proficiency in API implementation, web services, development testing, and deployment has contributed to the successful delivery of various client projects, such as Wethio Exchange, Hedgex Exchange, Envoychain payment gateway based on Stellar assets, and more. With a creative mind and excellent analytical skills, Himanshu enjoys staying up to date with the latest technologies and exploring new ideas to bring value to his work.

Request for Proposal

Name is required

Comment is required

Sending message..