1. Overview

In our previous article, we have explained Inversion of control and Dependency Injection with Spring.
In this article, we will introduce Spring JPA sorting & paging concepts and will provide simple and clear examples with images.

2. Development environment

Java: 1.8
Database: apache derby embedded database
Framework: hibernate, spring boot, spring data JPA
IDE: STS (Spring tool suite)
Note: embedded database will create when we start server and destroy when server stops.
It is for testing purpose and available within application.

3. Spring JPA sorting & paging

Before going to learn code and example, we will see what is sorting and paging(pagination) really means.

3.1 Sorting

Sorting means arranging elements of list in ascending or descending manner. Always sorting is almost to make stuff look nice for humans. Have a look at following image to get clarity.

Spring JPA sorting

3.2 Paging

Assume we have 1 million product details in the database. When user want see product details, we cannot show all product details at a time on the screen .so we will show 10 or 20 records at a time depends on the screen size. Google also does pagination(paging) because of it may have thousand results for your request. Have look at google pagination in the following the image

Spring-JPA-paging

 

4. Spring JPA sorting & paging examples

Spring Data JPA is a layer on top of the java persistence API (JPA). It provides repositories to perform basic crud operations, paging and sorting and more other operation like flush and clear etc.
Spring Data JPA provides repository PagingAndSortingRepository interface to do sorting and paging operations. PagingAndSortingRepositoryinterface extends CrudRepositoryinterface
See PagingAndSortingRepositoryinterface hierarchy in following the image

PagingAndSortingRepository has following methods to perform sorting and paging operations,

  1. Iterable<T> findAll(Sort sort);
  2. Page<T> findAll(Pageable pageable);
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> { 
        Iterable<T> findAll(Sort sort); 
        Page<T> findAll(Pageable pageable);
    }

Let assume we have an order table with data in Database like as follows,

ORDER_ID	ORDERED_BY	ORDER_AT	ORDERED_ITEM	DELIVERY_ADDRESS
1		Raju		1-10-2019	mobile		Bangalore
2		Jaanu		18-10-2019	bike		Delhi
3		Chandu		16-10-2019	car		Maharashtra
4		Kiran		11-10-2019	book		Chennai
5		Thomas		2-10-2019	shirt		Hyderabad
6		Rakesh		15-10-2019	watch		Pune
7		Ashesh		17-10-2019	tv		Goa
8		Namita		19-10-2019	Ac		Bangalore
9		Deepak		7-10-2019	sofa		Chandigarh
10		Eswar		13-10-2019	Earphones	Rajasthan
@Entity
@Table(name="Order")
public class OrderDo { 
    @Id
    @GeneratedValue
    @Column(name="ORDER_ID")
    private Long orderId;
 
    @Column(name="ORDERED_BY")
    private String orderedBy;
 
    @Column(name="ORDER_AT")
    private Date orderAt;
 
    @Column(name="ORDERED_ITEM")
    private String orderedItem;
 
    @Column(name="DELIVERY_ADRESS")
    private String deliveryAddress;
//setter,getter and toString methods
}

Now, we created project and project structure looks like,

4.1 Spring JPA Sorting Example

We want to display orders details in descending order of ordered date means recently ordered orders should come first. The query result will be like following data in table,

ORDER_ID	ORDERED_BY	ORDER_AT	ORDERED_ITEM	DELIVERY_ADDRESS
8		Namita		19-10-2019	Ac		Bangalore	
2		Jaanu		18-10-2019	bike		Delhi
7		Ashesh		17-10-2019	tv		Goa
3		Chandu		16-10-2019	car		Maharashtra
6		Rakesh		15-10-2019	watch		Pune
10		Eswar		13-10-2019	Earphones	Rajasthan
4		Kiran		11-10-2019	book		Chennai
9		Deepak		7-10-2019	sofa		Chandigarh
5		Thomas		2-10-2019	shirt		Hyderabad
1		Raju		1-10-2019	mobile		Bangalore

4.1.1 Code

Spring data JPA providing Sort class to accept sorting fileds and direction of ordering configuration. Sort has following methods

  1. public static Sort by (String… properties) ;
  2. public Sort descending ();
  3. public Sort ascending ();
Sort sort= Sort.by("orderAt");
sort=sort. descending ();
Iterable<OrderDo> orderIterator = orderRepository.findAll(sort);
                                        Or

Iterable<OrderDo> orderIterator = orderRepository.findAll(Sort.by("orderAt").descending());

4.2 Spring JPA Paging Example

Let’s assume we got requirement from the client saying display 5 records on the screen at time and when user click on next page or scroll the page show next 5 records. Continue same until no records available on the database.
It is very simple right we will take page number and page size from UI and we will query the table and send the response to the UI.

4.2.1 Code

Spring data JPA providing a Pageable interface which has a method to accept page number and page size configuration. PageRequest class is implementation for Pageable interface.

PageRequest has following methods

  1. public static PageRequest of (int page, int size);
  2. protected PageRequest of (int page, int size, Sort sort);

Code to get the first page with first five records,

Pageable paging = PageRequest.of(0, 5);
Page<OrderDo> page = orderRepository.findAll(paging);
                                     Or
Slice <OrderDo> page = orderRepository.findAll(paging);

Code to get next pages

Pageable paging = PageRequest.of(1, 5);
Pageable paging = PageRequest.of(2, 5);

Note: By default, return object is Page. we can get return object as Page type or Slice type.

The difference between Page type and Slice type is Pageinterface extends Sliceinterface

Page interface has following extra methods than slice interface

  1. long getTotalElements(); => to get the total number of elements in the database
  2. int getTotalPages(); => to get the total number of pages

Result:

ORDER_ID	ORDERED_BY	ORDER_AT	ORDERED_ITEM	DELIVERY_ADDRESS
1		Raju		1-10-2019	mobile		Bangalore
2		Jaanu		18-10-2019	bike		Delhi
3		Chandu		16-10-2019	car		Maharashtra
4		Kiran		11-10-2019	book		Chennai
5		Thomas		2-10-2019	shirt		Hyderabad

5. Spring JPA Paging with sorting example

We want to provide one feature to users like show last three recently ordered orders details.
To achieve this, first, we must sort the table by order date and next apply pagination.

5.1 Code

The pageable interface has an overloaded method to accept the Sort object along with page number and page size.

Sort sort = Sort.by("orderAt"). descending (); 
Pageable paging = PageRequest.of(0, 3, sort); 
Iterable<OrderDo> orderIterator = orderRepository.findAll(paging);

5.2 Output

ORDER_ID	ORDERED_BY	ORDER_AT	ORDERED_ITEM	DELIVERY_ADDRESS
8		Namita		19-10-2019	Ac		Bangalore
2		Jaanu		18-10-2019	bike		Delhi
7		Ashesh		17-10-2019	tv		Goa

Once you configure the project, you can run and test the functionality using following URL,

  1. http://localhost:8080/saveOrders
  2. http://localhost:8080/getAllOrders
  3. http://localhost:8080/getOrdersWithPagination?pageNumber=0&&pageSize=2
  4. http://localhost:8080/getLastThreeRecentOrders

6. Conclusion

We have presented sorting and paging concepts with real time examples with visualization by images.
Hope you like it 😊 if you want more information, go through the following link,

Spring Documentation

 

 

Was this post helpful?

Leave a Reply

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