Using SPRING-DATA-JPA for paging queries in spring boot

Source: Internet
Author: User

In our usual work, the query list is basically ubiquitous in our system, so how do we use JPA for multi-conditional queries and query list paging? I'll show you two ways to make a multi-conditional query.

1. Introduction of starting Dependence

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId> Spring-boot-starter-web</artifactid></dependency><dependency>    <groupId> Org.springframework.boot</groupid>    <artifactid>spring-boot-starter-thymeleaf</artifactid ></dependency><dependency>    <groupId>org.springframework.boot</groupId>    < Artifactid>spring-boot-starter-data-jpa</artifactid></dependency>

2. Configuration of Thymeleaf and JPA
Open Application.yml, add the following parameters, the following configuration is described in the previous article, there is no too much explanation here

Spring:thymeleaf:cache:trueCheck-template-location:truecontent-type:text/HTML Enabled:trueEncoding:utf-8MODE:HTML5 Prefix:classpath:/templates/suffix:. html excluded-view-names:template-resolver-Order:datasource:driver-class-name:com.mysql.jdbc.Driver Url:jdbc:mysql://Localhost:3306/restful?useunicode=true&characterencoding=utf-8&usessl=falseusername:root Password:root Initialize:trueInit-DB:trueJpa:database:mysql Show-sql:trueHIBERNATE:DDL-auto:update naming:strategy:org.hibernate.cfg.ImprovedNamingStrategy

3. Writing Entity Beans

@Entity @table (name= "book") public class Book {    @Id    @GeneratedValue (strategy = generationtype.identity)    @ Column (name = "id", updatable = False)    private Long ID;    @Column (nullable = False,name = "name")    private String name;    @Column (nullable = False,name = "ISBN")    Private String ISBN;    @Column (nullable = False,name = "Author")    private String author;    Public book (String name,string isbn,string author) { = name;        THIS.ISBN = ISBN; = author;    }    Public book () {    }    //Omit Get, set method}public class Bookquery {    private String name here;    Private String ISBN;    Private String author;    Get, set method} is omitted here


4. Write Repository interface

@Repository ("bookrepository") public interface Bookrepository extends Jparepository<book,long>        , jpaspecificationexecutor<book> {}


There are two interfaces inherited here, followed by a description of why these two interfaces are inherited

5. Abstract Service Layer
First, abstract out the interface

Public interface Bookqueryservice {    page<book> findbooknocriteria (Integer page,integer size);    Page<book> Findbookcriteria (Integer page,integer size,bookquery bookquery);}


Implementing interfaces

@Service (value= "Https://") public class Bookqueryserviceimpl    Implements Bookqueryservice {@Resource bookrepository bookrepository; @Override public page<book> Findbooknocriteria (Integer page,integer size) {pageable pageable = new Pagere        Quest (page, size, Sort.Direction.ASC, "id");    Return Bookrepository.findall (pageable);        } @Override Public page<book> findbookcriteria (integer Page, integer size, final bookquery bookquery) {        pageable pageable = new Pagerequest (page, size, Sort.Direction.ASC, "id");  page<book> bookpage = Bookrepository.findall (new specification<book> () {@Override public                predicate topredicate (root<book> Root, criteriaquery<?> query, Criteriabuilder criteriabuilder) {                list<predicate> list = new arraylist<predicate> (); if (Null!=bookquery.getname () &&! "". Equals (Bookquery.getnamE ())) {List.add (Criteriabuilder.equal (Root.get ("name"). As (String.class), Bookquery.getname ())); } if (NULL!=BOOKQUERY.GETISBN () &&! "". Equals (BOOKQUERY.GETISBN ())) {List.add (Criteriabuilder.equal (Root.get ("ISBN"). As (String.class), Bookque                RY.GETISBN ())); } if (Null!=bookquery.getauthor () &&! "". Equals (Bookquery.getauthor ())) {List.add (Criteriabuilder.equal (Root.get ("Author"). As (String.class), Boo                Kquery.getauthor ()));                } predicate[] P = new predicate[list.size ()];            Return Criteriabuilder.and (List.toarray (p));        }},pageable);    return bookpage; }}


Here I have defined two interfaces, Findbooknocriteria is not with the query condition, Findbookcriteria is with the query condition. Here is a description of the above mentioned custom repository inherited two interfaces, if your query list is no query criteria, just list display and paging, just inherit the Jparepository interface, However, if your query list is with multiple query criteria, you need to inherit the Jpaspecificationexecutor interface, which defines the method of the multi-conditional query. Of course, regardless of which interface you inherit, when you do paged query, you need to call the FindAll method, this method is the JAP definition of the paging query method.

Findbookcriteria method can also be implemented using the following methods, you can choose their own

@Override public    page<book> findbookcriteria (integer Page, integer size, final bookquery bookquery) {        pageable pageable = new Pagerequest (page, size, Sort.Direction.ASC, "id");        page<book> bookpage = Bookrepository.findall (new specification<book> () {            @Override            public predicate topredicate (root<book> Root, criteriaquery<?> query, Criteriabuilder criteriabuilder) {                predicate P1 = criteriabuilder.equal (root.get ("name"). As (String.class), Bookquery.getname ());                predicate P2 = criteriabuilder.equal (Root.get ("ISBN"). As (String.class), BOOKQUERY.GETISBN ());                predicate p3 = criteriabuilder.equal (Root.get ("Author"). As (String.class), Bookquery.getauthor ());                Query.where (Criteriabuilder.and (P1,P2,P3));                return query.getrestriction ();            }        },pageable);        return bookpage;    }


6. Write Controller
For the query conditions and no query conditions, we write a controller, the default per page display 5, as follows

@Controller @requestmapping (value = "Https://") public class Bookcontroller {@Autowired BOOKQ    Ueryservice Bookqueryservice; @RequestMapping ("/findbooknoquery") public String findbooknoquery (Modelmap modelmap, @RequestParam (value = "https://               ", defaultvalue =" ") Integer page, @RequestParam (value = "Https://", defaultvalue = "Https://        INCJ/BLOG/5 ") Integer size) {page<book> datas = Bookqueryservice.findbooknocriteria (page, size);        Modelmap.addattribute ("Datas", datas);    return "INDEX1"; } @RequestMapping (value = "Https://", method = {Requestmethod.get,}) Pu Blic String findbookquery (Modelmap modelmap, @RequestParam (value = "Https://", DefaultValue = "") Integer Page, @RequestParam (value = "Https://", DefaultValue = " HTTPS://MY.OSCHINA.NET/WANGXINCJ/BLOG/5 ") Integer size, bookquery bookquery) {page<book> datas = Bookqueryser        Vice.findbookcriteria (page, size,bookquery);        Modelmap.addattribute ("Datas", datas);    return "Index2"; }}


7. Write the page
First we write a generic paging page and create a new page called page.html.

<! DOCTYPE html><! DOCTYPE html>

For an interface with query criteria, create a page named index2.html and introduce the previously written paging page, as follows <! DOCTYPE html> 

Ok! The code is all done and we start the project and look at the effect. You can insert some data into the database, Access Http://localhost:8080/queryBook/findBookNoQuery, display the following page

To access Http://localhost:8080/queryBook/findBookQuery, display the page as follows, you can enter query criteria for a paged query with conditions:

Ok! The above is a simple Jap paging query function implementation.

Using SPRING-DATA-JPA in spring boot to implement paging queries (GO)

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: 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.