在使用Jhipster想实现用Pageable作为分页参数并返回Page对象时,需要注意的点是,这里page的值要从0开始
/api/company-users/withDelFlag?page=0&size=20
@GetMapping("/company-users/withDelFlag")
public ResponseEntity<List<CompanyUser>> getAllCompanyUsersWithDelFlag(Pageable pageable) {
log.debug("REST request to getAllCompanyUsersWithDelFlag");
List<CompanyUser> all = companyUserService.findAllWithDelFlag(pageable);
//封装Page对象
Page page = new PageImpl(all,pageable,all.size());
//构建HttpHeader
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
因为在构建Page对象时所用的实现类PageImpl构建total的值和构建HTTPHeader的值是相关的,
Header里记录了所查记录的总数
分页要求的三个参数都齐备的时候才能进行良好的分页,页码(page),每页条数(size),总条数(X-Total-Count)
然后是Limit分页
public List<CompanyUser> findCompanyUserAllWithDelFlagIsFalse(Pageable pageable) {
int pageNumber = pageable.getPageNumber();
int pageSize = pageable.getPageSize();
int start = pageNumber * pageSize;
String orderByWhat = "wcu.id";
String orderRule = "ASC";
if (! pageable.getSort().toString().equals("UNSORTED") ) {
String[] split = pageable.getSort().toString().split(":");
orderByWhat = split[0];
orderRule = split[1];
}
String sql = String.format(
"SELECT " +
" wcu.* " +
"FROM " +
"table_wcu wcu " +
"WHERE " +
"wcu.del_flag = false " +
"ORDER BY %s %s " +
"LIMIT %s, %s", orderByWhat , orderRule , start , pageSize);
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CompanyUser.class));
}