使用這種分頁方式,好像是比jpa或者MyBatis自帶的分頁工具有更好的性能和安全性,
需要接收的引數
public ApiResponse getBlackList(
@RequestParam(name = "pageSize", required = false) Integer pageSize,
@RequestParam(name = "cursor", required = false) String cursor) {
//pageSize 頁面容量
/*cursor 即偏移量,使用資料id或者某個專門用來分頁的欄位,比如上次查詢了id為5-10的資料,下一頁資料cursor的值應為10,service層的代碼查詢id >= cursor+1的資料,查詢的數量為pageSize個,如果沒有攜帶cursor,按照查詢第一頁處理*/
}
service
// 注:查詢的時候傳pageSize + 1是為了獲取下一頁第一條資料的id,回傳給前端作為下一頁的cursor傳過來
List<pojo> result = new ArrayList();
if(StringUtils.isBlank(cursor)) {
//查詢首頁
result = repository.findFirstPage(pageSize + 1);
}else {
Long longCursor = null;
try {
//解密cursor
byte[] decode = Base64.getUrlDecoder().decode(cursor);
//轉成Long型別
longCursor = new Long(new String(decode));
} catch (IllegalArgumentException e) {
log.warn("parameter [{}] type exception", cursor);
throw new IllegalArgumentException("Unexpeted value: cursor [" + cursor + "]");
}
//查詢
result = repository.findPage(pageSize + 1, longCursor);
if (result.size() > pageSize) {
// 洗掉最后一條資料,因為那是下一頁的第一條
Pojo pojo= result.get(result.size() - 1);
result.remove(pojo);
//獲取下一頁第一條id
Long id = pojo.getId();
//加密該id回傳給前端,用作下一頁的查詢
String newCursor = Base64.getUrlEncoder().encodeToString(String.valueOf(id).getBytes());
resultMap.put("cursor", newCursor);
}
}
repository
/*查找首頁*/
select * from table where '查詢條件' order by model.id limit :pageSize
/*分頁查詢*/
select * from table where '查詢條件' model.id>=:cursor order by model.id limit :pageSize
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/517511.html
標籤:Java
下一篇:Java 集合簡介 一
