AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Paging and sorting with Spring Data

In this article, we will see how we can perform pagination and sorting with Spring Data. Both pagination and sorting can be easily done using Spring Data.

Maven Dependency for Pagination and Sorting in Spring Data

The first step we need to take to use Spring Data is to add the dependency. If we are using the Spring Boot parent, all we need to add is its starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Once we have added this dependency, we can use pagination and sorting in Spring Data. The best way to understand it is through an example.

Example of Pagination and Sorting with Spring Data

Let’s see an example of how to perform sorting and pagination on a table stored in a database. Our table will be for users, and we will perform sorting by name and pagination.

Entity Creation

We create an entity in which we will use Lombok to simplify the boilerplate.

@Entity 
@Getter
@Setter
@NoArgsConstructor
public class User {
    
    @Id
    private long id;

    private String name;

}

Repository Creation

To create the repository to perform pagination and sorting, we can choose to:

  1. Extend PagingAndSortingRepository.
  2. Extend JpaRepository.

PagingAndSortingRepository provides the findAll methods for pagination and sorting.

On the other hand, if we extend JpaRepository, we will have a specific extension of the repository that includes CrudRepository and PagingAndSortingRepository.

public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>  

For our example, we will extend JpaRepository as follows:

public interface UserRepository extends JpaRepository<User, Long> {

    List<User> findAllByName(String name, Pageable pageable);
}

Once we have created our method for pagination and sorting, it’s time to use it.

Pagination with Spring Data

To use pagination in Spring Data, it is necessary to create a Pageable object that will be passed to the repository function we created.

To create a Pageable object, we will use PageRequest, which is an implementation of Pageable. Here’s the method we have in our repository:

public List<User> findUsesByName(String name, int initPage) {
 
   Pageable page = PageRequest.of(initPage, 10); //size = 10
   

   return userRepository.findAllByName(name, page);

}

In the above code snippet, we have created a Pageable object using PageRequest, to which we pass two values: the initial page and the page size. We then pass this Pageable object to the repository.

One of the default methods of the repository is findAll(), which returns a Page object that provides more information about pagination:

Page<User> allUsers = userRepository.findAll(page);

The Page interface would be as follows:





public interface Page<T> extends Slice<T>

The Page object, which extends Slice, provides us with a list as well as the total number of elements and the total number of pages for that search.

Sorting with Spring Data

To perform sorting, we can use two approaches:

  1. Using Sort.by("field").
  2. Passing Sort.by in PageRequest.

For example, using Sort.by would be as follows:

Page<User> allUsersSortByName = userRepository.findAll(Sort.by("name"));

Or we can sort while adding pagination with PageRequest:

Pageable sortedByName = PageRequest.of(init, 10, Sort.by("name"));

Pageable sortByNameInDescendentWay = PageRequest.of(0, 10, Sort.by("name").descending());

Pageable sortByNameAndAge = 
  PageRequest.of(init, end, Sort.by("age").descending().and(Sort.by("name")));

Additionally, something we can do is specify whether we want ascending (by default) or descending sorting. We can also perform compound sorting, for example, we can sort by name in descending order and then by age.

Conclusion

Spring Data makes pagination to obtain paginated and sorted lists easier. Performing pagination is very common when we want to retrieve lists and avoid fetching all records from the database.

Pagination in Spring Data improve our applications by avoiding issues with excessively long lists.

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

Your email address will not be published. Required fields are marked *