Mybatis3.3.x技术内幕(十三):Mybatis之RowBounds分页原理

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

RowBounds对象的源码以下:
sql

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的如何进行分页的。apache

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的分页是对结果集进行的分页。
app

假设查询结果总共是100条记录,而咱们只须要分页后的10条,是否是意味着100条记录在内存中,咱们对内存分页得到了10条数据呢?性能

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

所以,Mybatis的逻辑分页性能,并不像不少人想的那么差,不少人认为是对内存进行的分页。this


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

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

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

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


版权提示:文章出自开源中国社区,若对文章感兴趣,可关注个人开源中国社区博客(http://my.oschina.net/zudajun)。(通过网络爬虫或转载的文章,常常丢失流程图、时序图,格式错乱等,仍是看原版的比较好)

相关文章
相关标签/搜索