Data paging and sorting using Spring Data JPA

I. reading guidance

If thousands of list data are loaded at one time, it will be very time-consuming to display on the web page, and the user experience is not good. Therefore, paging query is essential when dealing with the display of large data query results. Paging query must be accompanied by certain sorting rules, otherwise the status of paging data is difficult to control, resulting in users may see the same data in different pages. So, the main content of this article is to introduce how to use Spring Data JPA for paging and sorting.

II. Entity definition

We use a simple entity definition: Article

public class Article {

    private Long id;

    @Column(nullable = false,length = 32)
    private String author;

    @Column(nullable = false, unique = true,length = 32)
    private String title;

    @Column(length = 512)
    private String content;

    private Date createTime;
  • @Entity indicates that this class is an entity class, which accepts JPA control management and corresponds to a table in the database.
  • @Table specifies the table name in the database corresponding to this class. If the class name and database table name meet the hump and underline rules, this annotation can be omitted. For example, the flow type class name corresponds to the table name flow U type.
  • @Id specifies this field as the primary key of the table
  • @GeneratedValue(strategy=GenerationType.IDENTITY) specifies the generation method of primary key. Generally, if the primary key is self increasing, the generation method of GenerationType.IDENTITY is used
  • @The Column annotation is for a field, corresponding to a Column in the table. nullable = false indicates that the database field cannot be empty, unique = true indicates that the database field cannot have duplicate values, and length = 32 indicates that the maximum extent of the database field is 32
  • @Data, @ AllArgsConstructor, @ NoArgsConstructor, @ Builder are annotations of plug-in lombok, which are used to help us generate template code of entity classes such as set, get method, constructor, etc.

III. definition of Repository

Define an interface ArticleRepository to inherit PagingAndSortingRepository. Pagingandsortingreposition interface not only contains basic CURD functions, but also supports interface function definitions of sorting and paging.

public interface ArticleRepository extends PagingAndSortingRepository<Article,Long> {
     //Query all the data in the article table, pass in the Pageable paging parameter, no need to write SQL by yourself
    Page<Article> findAll(Pageable pageable);
    //Query the article table data according to the author field, pass in the Pageable paging parameter, and do not need to write SQL by yourself
    Page<Article> findByAuthor(String author, Pageable pageable);
    //According to the author field and title field, query the article table data, pass in the Pageable paging parameter, and do not need to write SQL by yourself
    Slice<Article> findByAuthorAndTitle(String author, String title, Pageable pageable);

IV. paging

Pageable is an interface defined by Spring, which is used to pass paging parameters. Let's see how to use it. First, inject the ArticleRepository into the class you need to perform persistence layer operation, usually a @ Service annotation class, and then use the following code in the Service method to perform paging operation: query the data on the first page (starting from 0), 10 pieces of data per page.

Pageable pageable = PageRequest.of(0, 10);   //First page
//Pageable pageable = PageRequest.of(0, 10); / / page 2
//Pageable pageable = PageRequest.of(0, 10); / / page 3
//Database operation get query results
Page<Article> articlePage = articleRepository.findAll(pageable);
//Convert query results to List
List<Article> articleList = articlePage.getContent();

The findAll method responds with the object of the Page class. If we want to get the List of query results, we can use the getContent() method. However, I do not recommend this transformation, because the front-end displays a paging List, which requires not only data, but also paging information. For example: the current Page, how many items per Page, how many pages in total, how many items in total. This information is available in the Page(articlePage) object (described below).

V. implementation of sorting

Spring Data JPA provides a Sort object to provide a Sort mechanism. Let's take a look at the Sort.


  • The first findAll method sorts in ascending order of createTime
  • The first findAll method sorts in ascending order of the author, and then in descending order of createTime

Paging and sorting together

Pageable pageable = PageRequest.of(0, 10,"createTime"));

Vi. Slice and Page

In ArticleRepository, we see that one method returns Slice and another method returns Page. They are the data response interfaces of Spring Data JPA, where Page is the sub interface of Slice. They are used to save and return data.


Let's take a look at some important ways of Slice.

List <T>  getContent(); //Get the contents of the slice

Pageable  getPageable(); //Paging information for the current slice

boolean  hasContent(); //Is there any query result?

boolean  isFirst();  //Is it the first slice

boolean  isLast();  //Is it the last slice?

Pageable nextPageable(); // Paging information for next slice

Pageable previousPageable(); // Paging information of the previous slice


Page is the sub interface of Slice. Here are some important methods.

int getTotalPages();

//Total number of data
long getTotalElements();

So, when do you use Slice? When do I use Page?
Answer: from the function definitions of these two interfaces, it can be seen that Slice only cares whether there is the next partition (paging), and does not calculate the total number of entries and pages in the database count. Therefore, it is more suitable for mouse or finger sliding screen operation of large data list. It doesn't care how many pages there are in total, but only whether there is a next page. Page is more suitable for table development in traditional applications. You need to know the total number of pages and pages.

Looking forward to your attention

Tags: Java Database Spring SQL Lombok

Posted on Wed, 06 Nov 2019 16:45:13 -0800 by gtcol