Spring JPA 分頁

pb_yan發表於2018-06-04

     JPA本身提供分頁功能,前端傳過來pageable物件,也就是在路徑上新增?page=1&size=5這樣的引數(代表第一頁,每頁五個)。從controller層裡獲得Pageable pageable物件,然後一直傳到service層,dao層最後到repository中去。JPA會自動為我們分頁。如下例子一樣

    @Query(value = "select b from Banner b where  (b.enabled = ?1 or b.enabled = ?2) and b.operationType = 2 order by b.sortOrder asc")
    Page<Banner> findAllOpenClassBannerByEnabled(boolean enabled1,boolean enabled2,Pageable pageable);

    @Query(value = "select b from Banner b where  (b.enabled = ?1 or b.enabled = ?2) and b.operationType = 3 order by b.sortOrder asc")
    Page<Banner> findAllSpecialSubjectBannerByEnabled(boolean enabled1,boolean enabled2,Pageable pageable);

    @Query(value = "select b from Banner b where  (b.enabled = ?1 or b.enabled = ?2) and b.operationType = 1 order by b.sortOrder asc ")
    Page<Banner> findAllBannersByEnabled(boolean enabled1,boolean enabled2,Pageable pageable);

 還有一種使用原生SQL進行分頁,這種就比較麻煩一點。需要countQuery這個值來記錄value中的條數。簡單來說就是把value中的SQL語句中的數量統計出來。

  @Query(value = "SELECT * FROM  (SELECT * FROM banner WHERE (enabled = ?2 OR enabled = ?3)) AS a WHERE\n" +
            "operation_type = 1\n" +
            "AND FIND_IN_SET(?1, grade) order by id asc /* #pageable */",
            countQuery = "SELECT\n" +
                    "\tcount(*)\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\t*\n" +
                    "\t\tFROM\n" +
                    "\t\t\tbanner\n" +
                    "\t\tWHERE\n" +
                    "\t\t\t(enabled = ?2 OR enabled = ?3)\n" +
                    "\t) AS a\n" +
                    "WHERE\n" +
                    "\toperation_type = 1\n" +
                    "AND FIND_IN_SET(?1, grade)",
            nativeQuery = true)
    Page<Banner> findAllBannersByGrade(int grade,boolean enabled1,boolean enabled2,Pageable pageable);

相關文章