Spring JPA 分页

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值