使用這種分頁方式,好像是比jpa或者MyBatis自帶的分頁工具有更好的性能和安全性。 需要接收的參數 public ApiResponse getBlackList( @RequestParam(name = "pageSize", required = false) Integer pageSi ...
使用這種分頁方式,好像是比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