A, takeaway

If you load thousands of list data at once, displaying it on a web page will be time-consuming and the user experience will be poor. Therefore, when dealing with large data query results, paging query is essential. Paging queries must be accompanied by some sort of order, otherwise the state of paging data is difficult to control and users may see the same data on different pages. So, the main content of this article is to show you how to use Spring Data JPA for paging and sorting.

2. Entity definition

Let’s use a simple entity definition: Article

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name="article")
public class Article {

    @Id
    @GeneratedValue
    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;
}Copy the code
  • Entity indicates that this class is an Entity class that is managed by JPA and corresponds to a table in the database
  • @table specifies the name of the Table in the database that this class corresponds to. Omit this annotation if the class name and database table name comply with the hump and underscore rule. For example, FlowType class name corresponds to table name flow_type.
  • @id specifies this field as the primary key of the table
  • @GeneratedValue(Strategy =GenerationType.IDENTITY) specifies the generation mode of the primary key. Generationtype. IDENTITY is used if the primary key is auto-increment
  • The @column annotation is for a field that corresponds 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 value of the database field is 32.
  • @data, @Allargsconstructor, @Noargsconstructor, and @Builder are all annotations to the plugin Lombok to help us generate template code for entity classes such as sets, get methods, and constructors.

C) Repository definition

Define an interface ArticleRepository PagingAndSortingRepository inheritance. PagingAndSortingRepository interface contains basic CURD function not only, still support sorting, paging interface function definition.

Public interface ArticleRepository extends PagingAndSortingRepository < Article, Long > {/ / query Article table all of the data, the incoming Pageable paging parameters, SQL <Article> findAll(Pageable Pageable); Article < article > findByAuthor(String author, Pageable Pageable); Pageable < article > findByAuthor(String author, Pageable Pageable); // To query article table data based on the author and title fields, pass Pageable as the Pageable parameter, SQL Slice<Article> findByAuthorAndTitle(String author, String title, Pageable Pageable); }Copy the code

Four, to achieve paging

Pageable is the interface Spring defines for passing paging parameters; let’s see how to use it. First inject the ArticleRepository into the class where you need persistence, usually an @service annotation, and then paginate the Service method with the following code: query the first page (starting from 0) for 10 entries per page.

Pageable pageable = PageRequest.of(0, 10); Pageable Pageable = PageRequest. Of (0, 10); Pageable Pageable = PageRequest. Of (0, 10); / / / / database operations on Page 3 for the query results Page < Article > articlePage = articleRepository. The.findall (pageable); List List<Article> articleList = articlePage.getContent();Copy the code

The findAll method responds to an object of the Page class, and if we want to get the List of query results, we can use the getContent() method. But I don’t recommend doing this, because the front end presents a list of pages and requires not only data, but also some paging information. Such as: current pages, how many pages per page, how many pages in total, how many pages in total. All of this information is available in the articlePage object (described below).


Five, the implementation of sorting

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


articleRepository.findAll(Sort.by("createTime"));

articleRepository.findAll(Sort.by("author").ascending()
                        .and(Sort.by("createTime").descending()));
Copy the code
  • The first findAll method sorts createTime in ascending order
  • The first findAll method sorts author in ascending order and createTime in descending order

Paging and sorting go together

Pageable pageable = PageRequest.of(0, 10,Sort.by("createTime"));Copy the code

Slice and Page

In ArticleRepository we see one method returning Slice and another method returning Page. Both are Spring Data JPA Data response interfaces, where Page is a subinterface of Slice. Both are used to save and return data.

6.1.Slice

Let’s take a look at some important approaches to Slice.

List <T> getContent (); // To get the content of the slice; Pageable getPageable (); // Paging information for the current slice Boolean hasContent (); // Is there a query result? Boolean isFirst (); Boolean isLast (); // is the last slice Pageable nextPageable(); // next slice Pageable previousPageable(); // Paging information for the previous sliceCopy the code

6.2.Page

Page is a subinterface of Slice, and here are some important methods.

Int getTotalPages(); Long getTotalElements();Copy the code

So, when to use Slice? When to use Page? A: From the function definition of the two interfaces, Slice only cares about the existence of the next shard (paging), and does not count the total number of entries or pages in the database. Therefore, it is more suitable for the mouse or finger slide screen operation of the large data volume list. It does not care how many pages there are in total, but only whether there is a next page. Page is more suitable for traditional application table development, need to know the total number of pages and total number of articles.

We look forward to your attention

  • The blogger has recently written a new book: “SpringBoot Series – Chapter 16, Verse 97.”
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.