资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Mybatis之RowBounds分页原理详解

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

成都创新互联公司是工信部颁发资质IDC服务器商,为用户提供优质的雅安移动机房服务

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 resultContext = new DefaultResultContext();
  // 跳到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。

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


当前名称:Mybatis之RowBounds分页原理详解
标题URL:http://cdkjz.cn/article/pcidss.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220