Spring Data Jpa: Paging and sorting

Source: Internet
Author: User
Tags sort xmlns

Before we learned how to access a relational database using JPA. The development of our database has been greatly simplified through JPA. However, in the previous example we only mentioned the simplest crud (add-and-remove) operation. In fact, Spring Data JPA has perfect support for paging and sorting queries, and then we'll learn how to use pageable to page through a database for paged queries. Add maven Dependency

First we need to introduce JPA, the database directly using the HSQLDB memory database can be:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <parent> <groupid>org.springframework.boot</groupid&
        Gt <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> & lt;/parent> <groupId>tmy</groupId> <artifactId>demo.jpa.page</artifactId> <versi
        On>0.0.1-snapshot</version> <name>tmy-spring-jpa-page-demo</name> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SP ring-boot-starter-web</artifactid> </dependency> <dependency> <groupid&gt ; Org.springframework.boot</groUpid> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> &LT;ARTIFACTID&GT;HSQLDB&LT;/ARTIFAC tid> <scope>runtime</scope> </dependency> </dependencies> </project& Gt
Inherit Pagingandsortingrepository

The basic use of JPA in how to use JPA Access relational database has been introduced, we skip, here we directly look at the definition of interface blogrepository:

Public interface Blogrepository extends Pagingandsortingrepository<blog, integer> {
    
    page<blog> Findbydeletedfalse (pageable pageable);

}

As we can see, Blogrepository defines a method:page<blog> Findbydeletedfalse (pageable pageable), and we focus mainly on its parameters and the return value. Pageable is an interface defined in the Spring data library that is an abstraction of all paging-related information, through which we can get all the information related to paging (such as pagenumber, pagesize, etc.), so that JPA is able to get a SQL statement with paging information through the pageable parameter. The page class is also an interface provided by spring data, which represents a collection of data and related information about the next part of the data, the total number of data, through which we can get the overall information of the data (total number of data, total pages ...). ) and information about the current data (a collection of current data, the current number of pages, etc.)

In addition to using the naming conventions to help us extend SQL ' statements, Spring Data JPA also helps us to handle parameters of type pageable, convert the pageable parameter into a condition in the SQL ' statement, and also help us to handle the return value of type page. When the discovery return value type is page,spring data JPA will put the overall information of the data, the current data information, paging information into the return value. In this way, we can easily personalize the paging query.

Pageable is just an abstract interface, so home down we learn how to get pageable objects. generating pageable objects from parameters

Pageable defines a number of methods, but its core information is only two: the first is the paging information (page, size), and the second is the sorted information. Spring Data JPA provides a concrete implementation of pagerequest, and we only provide pagination and sorting information:

@RequestMapping (value = "/params", method=requestmethod.get) public
page<blog> Getentrybyparams (@ Requestparam (value = "Page", DefaultValue = "0") Integer page,
        @RequestParam (value = "Size", DefaultValue = "" ") Inte Ger size) {
    sort sort = new sort (DIRECTION.DESC, "id");
    pageable pageable = new Pagerequest (page, size, sort);
    Return Blogrepository.findall (pageable);
}

Here, we get the paging information through the parameters, and through sort and direction tell the pageable to sort by the ID in reverse order.

As you can see here, it is cumbersome to get a pageable object by parameters, which produces a lot of duplicate code when the query method is much more. To avoid this situation, Spring data provides a way to generate pageable directly. get the Pageable object directly

@RequestMapping (value = "", method=requestmethod.get) public
page<blog> getentrybypageable (@ Pageabledefault (value =, sort = {"id"}, Direction = Sort.Direction.DESC) 
    pageable pageable) {
    return Blogrepo Sitory.findall (pageable);
}

As we can see, we just need to define a parameter of type pageable directly in the parameter of the method, when spring finds this parameter, Spring automatically assembles the Pageable object according to the request parameter, Spring supports the request parameters as follows: page, page, starting from 0, default to page No. 0 size, size of each page, default to sort, sorting related information to Property,property (, asc| DESC) is organized in a way such as Sort=firstname&sort=lastname,desc, which is arranged in reverse order by LastName in the order of FirstName

In this way, we can use the parameters of the URL to do a variety of personalized query, and do not need to write a different method for each case.

Customizing the pageable by URL is convenient, but the only downside is that it's not beautiful, so we need to set a default configuration for pageable so that in many cases we can get information through a simple URL.

Spring provides the default configuration for @pageabledefault to help us personalize the settings pageable. For example @pageabledefault (value =, sort = {"id"}, direction = Sort.Direction.DESC) means that by default we are sorted in reverse order of ID, with a size of 15 per page. return Results

Finally, let's go to the root directory of the program and run the command

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.