Spring Boot Data JPA — Part II (Pagination and Sorting)

Mahesh Bonagiri
3 min readJul 20, 2021

Part I (Getting started)| Part III (Auditing) |Part IV (Projections)

In Previous post I explained how to get started with Spring boot Data JPA. In this post we will discuss how to use Pagination and Sorting with Spring Data.

Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks.

Also, we often need to sort that data by some criteria while paging.

Let’s start:

we will use Spring Initializer generate the base for our project, in my previous post I have explained how to get starting with Spring Boot + Eclipse.

Define a Simple Entity

Lets create an Entity called BookEntity as shown below.

Each of our Book instances has a unique identifier: id, its name, author and its price associated with it.

Repository Interface:

Let’s have a look at our BookRepoisitory, which extends the PagingAndSortingRepository, By extending PagingAndSortingRepository, BookRepository inherits findAll(Pageable pageable) and findAll(Sort sort) methods for working with Paging and Sorting. we can also add our own methods that take Pageable and Sort as parameters, like we did here with findByAuthor.

Let’s take a look at how to paginate our Books using these new methods.

Pagination:

Once we have our repository extending from PagingAndSortingRepository, Create a PageRequest object and pass it as an argument to the repository.

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

In the code above, we create a Pageable object with page 0 & size 2

Create an Application Class

Create SpringbootDataJpaPagingSortApplication class as shown below. Using CommandLineRunner we will first save few records and then later fetch those records.

When you run your application, you should see output similar to the following:

A Page<T> instance, in addition to having the list of Books, also knows about the total number of available pages. It triggers an additional count query to achieve it. By Enabling show_sql and format_sql we can see below queries in log.

Sorting:

Similarly, to just have our query results sorted, we can simply pass an instance of Sort to the method:

When you run your application, you should see output similar to the following

Pagination and Sorting

we can do both sorting and pagination by passing the sorting details into our PageRequest object itself. Based on our sorting requirements, we can specify the sort fields and the sort direction while creating our PageRequest instance.

Pageable sortByName = PageRequest.of(0, 2, Sort.by(“name”));
Pageable sortByPriceDesc = PageRequest.of(0, 2, Sort.by(“price”).descending());
Pageable sortByPriceDescNameAsc = PageRequest.of(0, 2, Sort.by(“price”).descending().and(Sort.by(“name”)));

Bonus Point:

The findAll(Pageable pageable) method by default returns a Page<T> object.

However, we can choose to return either a Page<T>, a Slice<T>, or a List<T> from any of our custom methods returning paginated data.

The main difference between Slice and Page is the latter provides non-trivial pagination details such as total number of records(getTotalElements()), total number of pages(getTotalPages()), and next-page availability status(hasNext()) that satisfies the query conditions, on the other hand, the former only provides pagination details such as next-page availability status(hasNext()) compared to its counterpart Page. Slice gives significant performance benefits when you deal with a colossal table with burgeoning records.

Use Page when UI/GUI expects to displays all the results at the initial stage of the search/query itself, with page numbers to traverse(ex., Bank Statement with page numbers)

Use Slice when UI/GUI does not interested to show all the results at the initial stage of the search/query itself, but intent to show the records to traverse based on scrolling or next button click event (ex., face book feed search)

Conclusion:

If you would like to refer to the full code, do check https://github.com/projectk-user1/Springboot-learning.git

Please do refer my other articles on Spring boot.

Feel free to provide your suggestions in comments section

--

--