最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

在Spring Boot中使用Spring-data-jpa實(shí)現(xiàn)分頁查詢

 更新時(shí)間:2017年07月21日 11:37:33   作者:zhengxiangwen  
如何使用jpa進(jìn)行多條件查詢以及查詢列表分頁呢?下面我將介紹兩種多條件查詢方式。具體實(shí)例代碼大家參考下本文吧

在我們平時(shí)的工作中,查詢列表在我們的系統(tǒng)中基本隨處可見,那么我們?nèi)绾问褂胘pa進(jìn)行多條件查詢以及查詢列表分頁呢?下面我將介紹兩種多條件查詢方式。

1、引入起步依賴  

<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、對(duì)thymeleaf和jpa進(jìn)行配置

打開application.yml,添加以下參數(shù),以下配置在之前的文章中介紹過,此處不做過多說明

spring: 
 thymeleaf: 
 cache: true 
 check-template-location: true 
 content-type: text/html 
 enabled: true 
 encoding: utf-8 
 mode: 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=false 
  username: root 
  password: root 
  initialize: true 
 init-db: true 
 jpa: 
  database: mysql 
  show-sql: true 
  hibernate: 
  ddl-auto: update 
  naming: 
   strategy: org.hibernate.cfg.ImprovedNamingStrategy 

3、編寫實(shí)體Bean

@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){ 
  this.name = name; 
  this.isbn = isbn; 
  this.author = author; 
 } 
 public Book(){ 
 } 
 //此處省去get、set方法 
} 
public class BookQuery { 
 private String name; 
 private String isbn; 
 private String author; 
 //此處省去get、set方法 
} 

4、編寫Repository接口

@Repository("bookRepository") 
public interface BookRepository extends JpaRepository<Book,Long> 
  ,JpaSpecificationExecutor<Book> { 
} 

此處繼承了兩個(gè)接口,后續(xù)會(huì)介紹為何會(huì)繼承這兩個(gè)接口

5、抽象service層

首先抽象出接口

public interface BookQueryService { 
 Page<Book> findBookNoCriteria(Integer page,Integer size); 
 Page<Book> findBookCriteria(Integer page,Integer size,BookQuery bookQuery); 
} 

實(shí)現(xiàn)接口

@Service(value="https://my.oschina.net/wangxincj/blog/bookQueryService") 
public class BookQueryServiceImpl implements BookQueryService { 
 @Resource 
 BookRepository bookRepository; 
 @Override 
 public Page<Book> findBookNoCriteria(Integer page,Integer size) { 
  Pageable pageable = new PageRequest(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), bookQuery.getIsbn())); 
    } 
    if(null!=bookQuery.getAuthor()&&!"".equals(bookQuery.getAuthor())){ 
     list.add(criteriaBuilder.equal(root.get("author").as(String.class), bookQuery.getAuthor())); 
    } 
    Predicate[] p = new Predicate[list.size()]; 
    return criteriaBuilder.and(list.toArray(p)); 
   } 
  },pageable); 
  return bookPage; 
 } 
} 

    此處我定義了兩個(gè)接口,findBookNoCriteria是不帶查詢條件的,findBookCriteria是帶查詢條件的。在此處介紹一下上面提到的自定義Repository繼承的兩個(gè)接口,如果你的查詢列表是沒有查詢條件,只是列表展示和分頁,只需繼承JpaRepository接口即可,但是如果你的查詢列表是帶有多個(gè)查詢條件的話則需要繼承JpaSpecificationExecutor接口,這個(gè)接口里面定義的多條件查詢的方法。當(dāng)然不管繼承哪個(gè)接口,當(dāng)你做分頁查詢時(shí),都是需要調(diào)用findAll方法的,這個(gè)方法是jap定義好的分頁查詢方法。

findBookCriteria方法也可以使用以下方法實(shí)現(xiàn),大家可以自行選擇

@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、編寫Controller

針對(duì)有查詢條件和無查詢條件,我們分別編寫一個(gè)Controller,默認(rèn)每頁顯示5條,如下

@Controller 
@RequestMapping(value = "https://my.oschina.net/queryBook") 
public class BookController { 
 @Autowired 
 BookQueryService bookQueryService; 
 @RequestMapping("/findBookNoQuery") 
 public String findBookNoQuery(ModelMap modelMap,@RequestParam(value = "https://my.oschina.net/wangxincj/blog/page", defaultValue = "https://my.oschina.net/wangxincj/blog/0") Integer page, 
      @RequestParam(value = "https://my.oschina.net/wangxincj/blog/size", defaultValue = "https://my.oschina.net/wangxincj/blog/5") Integer size){ 
  Page<Book> datas = bookQueryService.findBookNoCriteria(page, size); 
  modelMap.addAttribute("datas", datas); 
  return "index1"; 
 } 
 @RequestMapping(value = "https://my.oschina.net/findBookQuery",method = {RequestMethod.GET,RequestMethod.POST}) 
 public String findBookQuery(ModelMap modelMap, @RequestParam(value = "https://my.oschina.net/wangxincj/blog/page", defaultValue = "https://my.oschina.net/wangxincj/blog/0") Integer page, 
        @RequestParam(value = "https://my.oschina.net/wangxincj/blog/size", defaultValue = "https://my.oschina.net/wangxincj/blog/5") Integer size, BookQuery bookQuery){ 
  Page<Book> datas = bookQueryService.findBookCriteria(page, size,bookQuery); 
  modelMap.addAttribute("datas", datas); 
  return "index2"; 
 } 
} 

7、編寫頁面

首先我們編寫一個(gè)通用的分頁頁面,新建一個(gè)叫page.html的頁面

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org" 
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" 
  layout:decorator="page"> 
<body> 
<div th:fragment="pager"> 
 <div class="text-right" th:with="baseUrl=${#httpServletRequest.getRequestURL().toString()},pars=${#httpServletRequest.getQueryString() eq null ? '' : new String(#httpServletRequest.getQueryString().getBytes('iso8859-1'), 'UTF-8')}"> 
  <ul style="margin:0px;" class="pagination" th:with="newPar=${new Java.lang.String(pars eq null ? '' : pars).replace('page='+(datas.number), '')}, 
            curTmpUrl=${baseUrl+'?'+newPar}, 
            curUrl=${curTmpUrl.endsWith('&') ? curTmpUrl.substring(0, curTmpUrl.length()-1):curTmpUrl}" > 
   <!--<li th:text="${pars}"></li>--> 
   <li><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" >首頁</a></li> 
   <li th:if="${datas.hasPrevious()}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" >上一頁</a></li> 
   <!--總頁數(shù)小于等于10--> 
   <div th:if="${(datas.totalPages le 10) and (datas.totalPages gt 0)}" th:remove="tag"> 
    <div th:each="pg : ${#numbers.sequence(0, datas.totalPages - 1)}" th:remove="tag"> 
      <span th:if="${pg eq datas.getNumber()}" th:remove="tag"> 
       <li class="active"><span class="current_page line_height" th:text="${pg+1}">${pageNumber}</span></li> 
      </span> 
     <span th:unless="${pg eq datas.getNumber()}" th:remove="tag"> 
       <li><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" th:text="${pg+1}"></a></li> 
      </span> 
    </div> 
   </div> 
   <!-- 總數(shù)數(shù)大于10時(shí) --> 
   <div th:if="${datas.totalPages gt 10}" th:remove="tag"> 
    <li th:if="${datas.number-2 ge 0}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" th:text="${datas.number-1}"></a></li> 
    <li th:if="${datas.number-1 ge 0}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" th:text="${datas.number}"></a></li> 
    <li class="active"><span class="current_page line_height" th:text="${datas.number+1}"></span></li> 
    <li th:if="${datas.number+1 lt datas.totalPages}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" th:text="${datas.number+2}"></a></li> 
    <li th:if="${datas.number+2 lt datas.totalPages}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" th:text="${datas.number+3}"></a></li> 
   </div> 
   <li th:if="${datas.hasNext()}"><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" >下一頁</a></li> 
   <!--<li><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th: rel="external nofollow" >尾頁</a></li>--> 
   <li><a  rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="https://my.oschina.net/wangxincj/blog/${datas.totalPages le 0 ? curUrl+'page=0':curUrl+'&page='+(datas.totalPages-1)}" rel="external nofollow" >尾頁</a></li> 
   <li><span th:utext="'共'+${datas.totalPages}+'頁 / '+${datas.totalElements}+' 條'"></span></li> 
  </ul> 
 </div> 
</div> 
</body> 
</html> 

針對(duì)無查詢條件的接口,創(chuàng)建一個(gè)名為index1.html的頁面并引入之前寫好的分頁頁面,如下

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> 
<head> 
 <meta charset="UTF-8"/> 
 <title>Title</title> 
 <script type="text/javascript" th:src="https://my.oschina.net/wangxincj/blog/@{/jquery-1.12.3.min.js}"></script> 
 <script type="text/javascript" th:src="https://my.oschina.net/wangxincj/blog/@{/bootstrap/js/bootstrap.min.js}"></script> 
 <link type="text/css" rel="stylesheet" th: rel="external nofollow" rel="external nofollow" /> 
 <link type="text/css" rel="stylesheet" th: rel="external nofollow" rel="external nofollow" /> 
</head> 
<body> 
 <table class="table table-hover"> 
  <thead> 
  <tr> 
   <th>ID</th> 
   <th>name</th> 
   <th>isbn</th> 
   <th>author</th> 
  </tr> 
  </thead> 
  <tbody> 
  <tr th:each="obj : ${datas}"> 
   <td th:text="${obj.id}">${obj.id}</td> 
   <td th:text="${obj.name}">${obj.name}</td> 
   <td th:text="${obj.isbn}">${obj.isbn}</td> 
   <td th:text="${obj.name}">${obj.author}</td> 
  </tr> 
  </tbody> 
 </table> 
  <div th:include="page :: pager" th:remove="tag"></div> 
</body> 
</html> 

     針對(duì)有查詢條件的接口,創(chuàng)建一個(gè)名為index2.html的頁面并引入之前寫好的分頁頁面,如下  

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> 
<head> 
 <meta charset="UTF-8"/> 
 <title>Title</title> 
 <script type="text/javascript" th:src="https://my.oschina.net/wangxincj/blog/@{/jquery-1.12.3.min.js}"></script> 
 <script type="text/javascript" th:src="https://my.oschina.net/wangxincj/blog/@{/bootstrap/js/bootstrap.min.js}"></script> 
 <link type="text/css" rel="stylesheet" th: rel="external nofollow" rel="external nofollow" /> 
 <link type="text/css" rel="stylesheet" th: rel="external nofollow" rel="external nofollow" /> 
</head> 
<body> 
<form th:action="@{/queryBook/findBookQuery}" th:object="${bookQuery}" th:method="get"> 
 <div class="form-group"> 
  <label class="col-sm-2 control-label" >name</label> 
  <div class="col-sm-4"> 
   <input type="text" class="form-control" id="name" placeholder="請(qǐng)輸入名稱" th:field="*{name}"/> 
  </div> 
  <label class="col-sm-2 control-label">isbn</label> 
  <div class="col-sm-4"> 
   <input type="text" class="form-control" id="isbn" placeholder="請(qǐng)輸ISBN" th:field="*{isbn}"/> 
  </div> 
 </div> 
 <div class="form-group"> 
  <label class="col-sm-2 control-label" >author</label> 
  <div class="col-sm-4"> 
   <input type="text" class="form-control" id="author" placeholder="請(qǐng)輸author" th:field="*{author}"/> 
  </div> 
  <div class="col-sm-4"> 
   <button class="btn btn-default" type="submit" placeholder="查詢">查詢</button> 
  </div> 
 </div> 
</form> 
 <table class="table table-hover"> 
  <thead> 
  <tr> 
   <th>ID</th> 
   <th>name</th> 
   <th>isbn</th> 
   <th>author</th> 
  </tr> 
  </thead> 
  <tbody> 
  <tr th:each="obj : ${datas}"> 
   <td th:text="${obj.id}">${obj.id}</td> 
   <td th:text="${obj.name}">${obj.name}</td> 
   <td th:text="${obj.isbn}">${obj.isbn}</td> 
   <td th:text="${obj.name}">${obj.author}</td> 
  </tr> 
  </tbody> 
 </table> 
  <div th:include="page :: pager" th:remove="tag"></div> 
</body> 
</html> 

ok!代碼都已經(jīng)完成,我們將項(xiàng)目啟動(dòng)起來,看一下效果。大家可以往數(shù)據(jù)庫中批量插入一些數(shù)據(jù),訪問

http://localhost:8080/queryBook/findBookNoQuery,顯示如下頁面

訪問http://localhost:8080/queryBook/findBookQuery,顯示頁面如下,可以輸入查詢條件進(jìn)行帶條件的分頁查詢:

總結(jié)

以上所述是小編給大家介紹的在Spring Boot中使用Spring-data-jpa實(shí)現(xiàn)分頁查詢,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • spring security實(shí)現(xiàn)下次自動(dòng)登錄功能過程解析

    spring security實(shí)現(xiàn)下次自動(dòng)登錄功能過程解析

    這篇文章主要介紹了spring security實(shí)現(xiàn)記住我下次自動(dòng)登錄功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • 通過實(shí)例了解java TransferQueue

    通過實(shí)例了解java TransferQueue

    這篇文章主要介紹了TransferQueue實(shí)例,下面小編和大家一起來學(xué)習(xí)一下
    2019-05-05
  • java 解析由String類型拼接的XML文件方法

    java 解析由String類型拼接的XML文件方法

    今天小編就為大家分享一篇java 解析由String類型拼接的XML文件方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Java面試題目集錦

    Java面試題目集錦

    本文是小編日常收集整理的java面試題目,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-09-09
  • 解決springboot啟動(dòng)成功,但訪問404的問題

    解決springboot啟動(dòng)成功,但訪問404的問題

    這篇文章主要介紹了解決springboot啟動(dòng)成功,但訪問404的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • SharedWorkerGlobalScope屬性數(shù)據(jù)共享示例解析

    SharedWorkerGlobalScope屬性數(shù)據(jù)共享示例解析

    這篇文章主要為大家介紹了SharedWorkerGlobalScope屬性數(shù)據(jù)共享示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • 利用Java對(duì)比兩個(gè)PDF文件之間的差異

    利用Java對(duì)比兩個(gè)PDF文件之間的差異

    這篇文章主要為大家詳細(xì)介紹了如何在 Java 程序中通過代碼快速比較兩個(gè) PDF 文檔并找出文檔之間的內(nèi)容差異,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-10-10
  • Java 實(shí)戰(zhàn)項(xiàng)目錘煉之在線美食網(wǎng)站系統(tǒng)的實(shí)現(xiàn)流程

    Java 實(shí)戰(zhàn)項(xiàng)目錘煉之在線美食網(wǎng)站系統(tǒng)的實(shí)現(xiàn)流程

    讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實(shí)現(xiàn)一個(gè)在線美食網(wǎng)站系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平
    2021-11-11
  • Java?數(shù)據(jù)庫連接池DBPool?介紹

    Java?數(shù)據(jù)庫連接池DBPool?介紹

    這篇文章主要給大家分享了Java?數(shù)據(jù)庫連接池DBPool?介紹,<BR>DBPool是一個(gè)高效的易配置的數(shù)據(jù)庫連接池。它除了支持連接池應(yīng)有的功能之外,還包括了一個(gè)對(duì)象池使你能夠開發(fā)一個(gè)滿足自已需求的數(shù)據(jù)庫連接池,下面一起來看看文章內(nèi)容的詳細(xì)介紹吧,需要的朋友可以參考一下
    2021-11-11
  • Java中使用BigDecimal進(jìn)行精確運(yùn)算

    Java中使用BigDecimal進(jìn)行精確運(yùn)算

    這篇文章主要介紹了Java中使用BigDecimal進(jìn)行精確運(yùn)算的方法,非常不錯(cuò),需要的朋友參考下
    2017-02-02

最新評(píng)論

洞头县| 英山县| 丰台区| 万源市| 舟山市| 新密市| 徐水县| 四会市| 望城县| 南投市| 竹溪县| 江津市| 当雄县| 朝阳市| 上饶县| 台山市| 刚察县| 来安县| 偃师市| 莱阳市| 乐陵市| 河南省| 南乐县| 鄂伦春自治旗| 延津县| 屯留县| 兴和县| 环江| 古蔺县| 思南县| 东方市| 界首市| 新和县| 梓潼县| 东城区| 兰溪市| 长海县| 惠安县| 娄底市| 中西区| 新建县|