當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot2.0 JPA 实现分页(简单查询分页、复杂查询分页)
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot2.0 JPA 实现分页(简单查询分页、复杂查询分页)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、簡單分頁(只有一個查詢條件)
- 在Repository層將查詢語句的返回值類型設置為為Page類型,查詢參數中加入Pageable pageable,如:
- 在Service層中實例化Pageable對象,并指定currentPage(當前頁)、pageSize(每頁最大容量),其中PageRequest.of為Spring Boot 2.0的方法,之前版本為new PageRequest(),如:
- 在Service層中實例化Pageable對象,并指定currentPage(當前頁)、pageSize(每頁最大容量),其中PageRequest.of為Spring Boot 2.0的方法,之前版本為new PageRequest(),如:
- 在Controller層設置相應的接口,由于currentPage規定從0開始,而前端通常返回的是從1開始,需要同步一下
二、多條件查詢分頁
多條件查詢采用的是以元模型概念為基礎的Criteria 查詢方法
- Repository層繼承JpaSpecificationExecutor<實體名>,并將返回類型改為Page類型,如:
- 在Service層構建Specification方法,具體實現見代碼,同樣Spring Boot 2.0和Spring Boot 2.0之前的方法有差異,簡單介紹一下各字段的含義:
- root:查詢根,指實體(此處為CloudServerDao),root.get(“userId”)為獲取實體(此處為CloudServerDao)中的字段userId,第二個userId為函數的參數
- Predicate:定義查詢條件。Predicate 對象通過調用CriteriaBuilder的條件方法( equal,notEqual, gt, ge,lt, le,between,like等)創建,具體方法自行搜索
spring boot 2.0推薦寫法
使用repository的findAll(specification, pageable)查詢即可
↓ Spring Boot 2.0之前的寫法,Spring Boot 2.0也適用,但是2.0版本推薦使用上面的方式 ↑
Specification<CloudServerDao> specification = new Specification<CloudServerDao>() {public Predicate toPredicate(Root<CloudServerDao> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {List<Predicate> list = new ArrayList<>();Predicate p1 = criteriaBuilder.equal(root.get("userId"),userId);list.add(p1);if (!key.equals(null)) {Predicate p2 = criteriaBuilder.like(root.get("serverName"),"%"+key+"%" );list.add(p2);}return criteriaBuilder.and(list.toArray(new Predicate[0]));}};return cloudServerRepository.findAll(specification, pageable);- 在Controller層設置和簡單查詢的配置一致
總結
以上是生活随笔為你收集整理的Spring Boot2.0 JPA 实现分页(简单查询分页、复杂查询分页)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MybatisPlus代码生成器配置
- 下一篇: 01 | Spring Data JPA