When we perform bulk operations, like finding all "Person"s 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.
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.
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:
In your custom repository, extend PagingAndSortingRepository.
Create a PageRequestobject, which is an implementation of the Pageableinterface
This PageRequest object takes the page number, the page size, and sorts direction and sort field.
By passing requested page number and page limit you can get the data for this page.
If you pass a 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.
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");
count(person0_.id) as col_0_0_
person0_.id as id1_1_,
person0_.country as country2_1_,
person0_.gender as gender3_1_,
person0_.name as name4_1_
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.