1. 程式人生 > 程式設計 >Mybatis之RowBounds分頁原理詳解

Mybatis之RowBounds分頁原理詳解

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。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。