温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Mybatis之RowBounds分页原理详解

发布时间:2020-08-30 12:46:07 来源:脚本之家 阅读:632 作者:祖大俊 栏目:编程语言

Mybatis可以通过传递RowBounds对象,来进行数据库数据的分页操作,然而遗憾的是,该分页操作是对ResultSet结果集进行分页,也就是人们常说的逻辑分页,而非物理分页。

RowBounds对象的源码如下:

public class RowBounds {

 public static final int NO_ROW_OFFSET = 0;
 public static final int NO_ROW_LIMIT = Integer.MAX_VALUE;
 public static final RowBounds DEFAULT = new RowBounds();

 private int offset;
 private int limit;

 public RowBounds() {
  this.offset = NO_ROW_OFFSET;
  this.limit = NO_ROW_LIMIT;
 }

 public RowBounds(int offset, int limit) {
  this.offset = offset;
  this.limit = limit;
 }

 public int getOffset() {
  return offset;
 }

 public int getLimit() {
  return limit;
 }

}

对数据库数据进行分页,依靠offset和limit两个参数,表示从第几条开始,取多少条。也就是人们常说的start,limit。

下面看看Mybatis的如何进行分页的。

org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap()方法源码。

 private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
   throws SQLException {
  DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
  // 跳到offset位置,准备读取
  skipRows(rsw.getResultSet(), rowBounds);
  // 读取limit条数据
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
   ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
   Object rowValue = getRowValue(rsw, discriminatedResultMap);
   storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
 }
 
  private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
  if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
   if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
    // 直接定位
    rs.absolute(rowBounds.getOffset());
   }
  } else {
   // 只能逐条滚动到指定位置
   for (int i = 0; i < rowBounds.getOffset(); i++) {
    rs.next();
   }
  }
 }

说明,Mybatis的分页是对结果集进行的分页。

假设查询结果总共是100条记录,而我们只需要分页后的10条,是不是意味着100条记录在内存中,我们对内存分页获得了10条数据呢?

非也,JDBC驱动并不是把所有结果加载至内存中,而是只加载小部分数据至内存中,如果还需要从数据库中取更多记录,它会再次去获取部分数据,这就是fetch size的用处。和我们从银行卡里取钱是一个道理,卡里的钱都是你的,但是我们一次取200元,用完不够再去取,此时我们的fetch size = 200元。

因此,Mybatis的逻辑分页性能,并不像很多人想的那么差,很多人认为是对内存进行的分页。

最优方案,自然是物理分页了,也就是查询结果,就是我们分页后的结果,性能是最好的。如果你一定要物理分页,该如何解决呢?

1. Sql中带有offset,limit参数,自己控制参数值,直接查询分页结果。

2. 使用第三方开发的Mybatis分页插件。

3. 修改Mybatis源码,给Sql追加自己的物理分页Subsql。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI