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);