溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Mybatis之RowBounds分頁原理詳解

發布時間:2020-08-30 12:46:07 來源:腳本之家 閱讀:698 作者:祖大俊 欄目:編程語言

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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女