Mybatis之RowBounds分页原理详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis之RowBounds分页原理详解

  2021-04-02 我要评论

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。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们