欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

使用偏移量的方式进行分页查询,

来源: javaer 分享于  点击 47955 次 点评:171

使用偏移量的方式进行分页查询,


注意:
这种方式分页查询前提是有排序字段且该字段是连续的,否则该方式查询指定页码数据时查询的数据是不对的

优势:
根据id字段分页时,本方法先select该数据,再向后偏移查询数据,可以使用主键索引进行查询,在数据量比较大的表中,本方法具有性能优势

需要接收的参数

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
相关栏目:

用户点评