Spring Boot2.0 JPA 實現分頁(簡單查詢分頁、復雜查詢分頁)

一、簡單分頁(只有一個查詢條件)

  • 在Repository層將查詢語句的返回值類型設置為為Page類型,查詢參數中加入Pageable pageable,如:
@Repository
public interface SshRepository extends JpaRepository<SshDao, Integer> {
    @Query("select s from ssh s where s.userId = :userId")
    Page<SshDao> selectAllByUserId(@Param("userId") Integer userId, Pageable pageable);
}
  • 在Service層中實例化Pageable對象,并指定currentPage(當前頁)、pageSize(每頁最大容量),其中PageRequest.of為Spring Boot 2.0的方法,之前版本為new PageRequest(),如:
public ResultDao getSsh(Integer userId, Integer currentPage, Integer pageSize) {
        // spring boot 2.0推薦寫法
        Pageable pageable = PageRequest.of(currentPage,pageSize);
        // spring boot 2.0 以前,2.0版本也適用,但是2.0版本推薦使用上面的方式
        // Pageable pageable = new PageRequest(currentPage,pageSize);
        
        return ResultUtil.unitedResult(ResultEnum.SUCCESS,sshRepository.selectAllByUserId(userId, pageable));
    }
  • 在Controller層設置相應的接口,由于currentPage規定從0開始,而前端通常返回的是從1開始,需要同步一下
@GetMapping("/ssh")
    public ResultDao getSsh(@PathParam("userId") Integer userId,
                            @PathParam("currentPage") Integer currentPage,
                            @PathParam("pageSize") Integer pageSize) {
        // 同步前端傳回的當前頁參數
        currentPage = currentPage - 1;
        return cloudServerService.getSsh(userId, currentPage, pageSize);
    }

二、多條件查詢分頁

多條件查詢采用的是以元模型概念為基礎的Criteria 查詢方法
  • Repository層繼承JpaSpecificationExecutor<實體名>,并將返回類型改為Page類型,如:
@Repository
public interface CloudServerRepository extends JpaRepository<CloudServerDao, Integer>,JpaSpecificationExecutor<CloudServerDao> {
}
  • 在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)查詢即可

// 代碼通過userId和key兩個條件進行查詢

public ResultDao getServer(String key, Integer userId, Integer currentPage, Integer pageSize) {
        Pageable pageable = PageRequest.of(currentPage,pageSize);
        Specification<CloudServerDao> specification = (Specification<CloudServerDao>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            // 第一個userId為CloudServerDao中的字段,第二個userId為參數
            Predicate p1 = criteriaBuilder.equal(root.get("userId"),userId);
            list.add(p1);
            if (!key.equals(null)) {
                // 此處為查詢serverName中含有key的數據
                Predicate p2 = criteriaBuilder.like(root.get("serverName"),"%"+key+"%" );
                list.add(p2);
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return cloudServerRepository.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層設置和簡單查詢的配置一致
@GetMapping("/ssh")
    public ResultDao getSsh(@PathParam("userId") Integer userId,
                            @PathParam("currentPage") Integer currentPage,
                            @PathParam("pageSize") Integer pageSize) {
        // 同步前端傳回的當前頁參數
        currentPage = currentPage - 1;
        return cloudServerService.getSsh(userId, currentPage, pageSize);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,886評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,941評論 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,522評論 1 92
  • 昨天,刪去。 今天,留著。 明天,爭取。 對的,堅持。 錯的,放棄。 你再優秀也會有人對你不屑一顧,你再不堪也會有...
    隨風飄搖閱讀 153評論 0 1
  • # 終端登陸: 1、'$ /usr/local/mysql/bin/mysql -u root -p' 終端登陸M...
    SnorlaxSE閱讀 398評論 0 0