JPA分页查询–自定义sql
1、在Dao层中自定义一个findPage()方法
使用@Query
注解,并且说明是原生sql,之后加上自定义Sql语句,并且还要加上countQuery
属性来获取总共查询了多少记录(这是重点不要忘了)
@Query(nativeQuery = true,
value = "SELECT bu.id," +
" bu.username," +
" bu.mobile," +
" bu.work_number workNumber," +
" bu.department_name departmentName," +
" bu.time_of_entry timeOfEntry," +
" bu.time_of_dimission leaveTime, " +
" ssuss.participating_in_the_city participatingInTheCity," +
" ssuss.participating_in_the_city_id participatingInTheCityId," +
" ssuss.provident_fund_city_id providentFundCityId, " +
" ssuss.provident_fund_city providentFundCity," +
" ssuss.social_security_base socialSecurityBase," +
" ssuss.provident_fund_base providentFundBase FROM bs_user bu LEFT JOIN ss_user_social_security ssuss ON bu.id=ssuss.user_id WHERE bu.company_id=1",
countQuery = "select count(*) from bs_user LEFT JOIN ss_user_social_security suss ON bs_user.id = suss.user_id where company_id = 1")
Page<Map> findPage(Pageable pageable);
- 以上代码中返回类
Page<Map>
表示,数据库查询的结果中列名映射到Map的key,列值映射到Map的value,这样与直接指定Page
为某一个实体类型
的作用是一样的,反而使用更加具有通用性。
2、Service层中,分页列表方法 接受两个参数:当前页码 和 页的大小,使用PageRequest.of()方法来获取Pageable对象
PageResult类型:自定义分页返回结果:总页数,当前页内容列表
Page page1 = Dao.findPage(Request.of(page,pageSize));
PageResult = new PageResult(page1.getTotalElements(), page1.getContent());
注意,PageResult类型的返回对象中,当前页内容是一个Map,但由于在controller层通过response返回时,会被转成JSON因此使用Map和使用自定义一个response类型的效果是一样的。