溫馨提示×

溫馨提示×

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

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

RowBounds分頁原理是什么

發(fā)布時間:2023-04-25 10:32:26 來源:億速云 閱讀:111 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“RowBounds分頁原理是什么”,在日常操作中,相信很多人在RowBounds分頁原理是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”RowBounds分頁原理是什么”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

    背景說明

    項目中經(jīng)常會使用分頁查詢,有次使用了RowBounds進行分頁,因為很多場景或網(wǎng)上也看到很多這樣的寫法,所以我也在項目中使用了該類進行分頁。

    但是有次線上卻拋了異常,由此引發(fā)了對RowBounds原理的探究。

    RowBounds是將所有符合條件的數(shù)據(jù)全都查詢到內(nèi)存中,然后在內(nèi)存中對數(shù)據(jù)進行分頁,若數(shù)據(jù)量大,千萬別使用RowBounds

    如我們寫的sql語句:

    select * from user where id>0 limit 0,10

    RowBounds會將id>0的所有數(shù)據(jù)全都加載到內(nèi)存中,然后截取前10行,若id>0有100萬條,則100萬條數(shù)據(jù)都會加載到內(nèi)存中,從而造成內(nèi)存OOM。

    一:RowBounds分頁原理

    Mybatis可以通過傳遞RowBounds對象,來進行數(shù)據(jù)庫數(shù)據(jù)的分頁操作,然而遺憾的是,該分頁操作是對ResultSet結(jié)果集進行分頁,也就是人們常說的邏輯分頁,而非物理分頁(物理分頁當然就是我們在sql語句中指定limit和offset值)。

    RowBounds源碼如下:

    public class RowBounds {
      /* 默認offset是0**/
      public static final int NO_ROW_OFFSET = 0;
      /* 默認Limit是int的最大值,因此它使用的是邏輯分頁**/
      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;
      }
    
    }

    對數(shù)據(jù)庫數(shù)據(jù)進行分頁,依靠offset和limit兩個參數(shù),表示從第幾條開始,取多少條。也就是人們常說的start,limit。

    下面看看Mybatis的如何進行分頁的。

    org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap()方法源碼。

    Mybatis中使用RowBounds實現(xiàn)分頁的大體思路:

    先取出所有數(shù)據(jù),然后游標移動到offset位置,循環(huán)取limit條數(shù)據(jù),然后把剩下的數(shù)據(jù)舍棄。

    private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
          throws SQLException {
      DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
    //跳過RowBounds設置的offset值
       skipRows(rsw.getResultSet(), rowBounds);
    //判斷數(shù)據(jù)是否小于limit,如果小于limit的話就不斷的循環(huán)取值
       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 boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) throws SQLException {
        //判斷數(shù)據(jù)是否小于limit,小于返回true
        return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
    }
    
      //跳過不需要的行,應該就是rowbounds設置的limit和offset
      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 {
          //跳過RowBounds中設置的offset條數(shù)據(jù),只能逐條滾動到指定位置
          for (int i = 0; i < rowBounds.getOffset(); i++) {
            rs.next();
          }
        }
    }

    二:RowBounds的使用

    原理:攔截器。

    使用方法:

    RowBounds:在dao.java中的方法中傳入RowBounds對象。

    2.1:引入依賴

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    2.2:service層

    import org.apache.ibatis.session.RowBounds;
    
    public class UserServiceImpl implements UserService {
        @Autowired
        private UserDao userDao;
        
        @Override
        public Map<String, Object> queryUserList(String currentPage, String pageSize) {
            //查詢數(shù)據(jù)總條數(shù)
            int total = userDao.queryCountUser();
            //返回結(jié)果集
            Map<String,Object> resultMap = new HashMap<String,Object>();
            
            resultMap.put("total", total);
            //總頁數(shù)
            int totalpage = (total + Integer.parseInt(pageSize) - 1) / Integer.parseInt(pageSize);
            resultMap.put("totalpage", totalpage);
            
            //數(shù)據(jù)的起始行
            int offset = (Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize);
            RowBounds rowbounds = new RowBounds(offset, Integer.parseInt(pageSize));
            //用戶數(shù)據(jù)集合
            List<Map<String, Object>> userList = userDao.queryUserList(rowbounds);
            
            resultMap.put("userList", userList);
            
            return resultMap;
        }
    
    }

    2.3:dao層

    import org.apache.ibatis.session.RowBounds;
    
    public interface UserDao {
        
        public int queryCountUser();       //查詢用戶總數(shù)
        public List<Map<String, Object>> queryUserList(RowBounds rowbounds);    //查詢用戶列表
    }

    2.4:mapper.xml

    mappep.xml里面正常配置,不用對rowBounds任何操作。

    mybatis的攔截器自動操作rowBounds進行分頁。

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.test.mapper.UserDao">
        
        <!-- 查詢用戶總數(shù) -->
        <select id="queryCountUser" resultType="java.lang.Integer">
            select count(1) from user
        </select>
        
        <!-- 查詢用戶列表 -->
        <select id="queryUserList" resultType="java.util.Map">
            select * from user
        </select>
        
    </mapper>

    三:RowBounds的坑

    2021-11-19 15:15:14.933 ERROR [task-10] [org.springframework.transaction.interceptor.TransactionInterceptor] Application exception overridden by rollback exception
    org.springframework.dao.TransientDataAccessResourceException:
    &mdash; Error querying database. Cause: java.sql.SQLException: Java heap space
    &mdash; The error may exist in com/test/mapper/InfoRecordMapper.java (best guess)
    &ndash; The error may involve com.test.mapper.InfoRecordMapper.selectByExampleAndRowBounds-Inline
    &mdash; The error occurred while setting parameters

    RowBounds是將所有符合條件的數(shù)據(jù)全都查詢到內(nèi)存中,然后在內(nèi)存中對數(shù)據(jù)進行分頁

    如我們查詢user表中id>0的數(shù)據(jù),然后分頁查詢sql如下:

    select * from user where id >0 limit 3,10

    但使用RowBounds后,會將id>0的所有數(shù)據(jù)都加載到內(nèi)存中,然后跳過offset=3條數(shù)據(jù),截取10條數(shù)據(jù)出來,若id>0的數(shù)據(jù)有100萬,則100w數(shù)據(jù)都會被加載到內(nèi)存中,從而造成內(nèi)存OOM。

    所以當數(shù)據(jù)量非常大時,一定要慎用RowBounds類。

    到此,關于“RowBounds分頁原理是什么”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

    AI