RowBounds分页原理是什么

其他教程   发布日期:2025年04月14日   浏览次数:95

这篇文章主要介绍“RowBounds分页原理是什么”,在日常操作中,相信很多人在RowBounds分页原理是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”RowBounds分页原理是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

    背景说明

    项目中经常会使用分页查询,有次使用了RowBounds进行分页,因为很多场景或网上也看到很多这样的写法,所以我也在项目中使用了该类进行分页。

    但是有次线上却抛了异常,由此引发了对RowBounds原理的探究。

    RowBounds是将所有符合条件的数据全都查询到内存中,然后在内存中对数据进行分页,若数据量大,千万别使用RowBounds

    如我们写的sql语句:

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

    RowBounds会将id>0的所有数据全都加载到内存中,然后截取前10行,若id>0有100万条,则100万条数据都会加载到内存中,从而造成内存OOM。

    一:RowBounds分页原理

    Mybatis可以通过传递RowBounds对象,来进行数据库数据的分页操作,然而遗憾的是,该分页操作是对ResultSet结果集进行分页,也就是人们常说的逻辑分页,而非物理分页(物理分页当然就是我们在sql语句中指定limit和offset值)。

    RowBounds源码如下:

    1. public class RowBounds {
    2. /* 默认offset是0**/
    3. public static final int NO_ROW_OFFSET = 0;
    4. /* 默认Limit是int的最大值,因此它使用的是逻辑分页**/
    5. public static final int NO_ROW_LIMIT = Integer.MAX_VALUE;
    6. public static final RowBounds DEFAULT = new RowBounds();
    7. private int offset;
    8. private int limit;
    9. public RowBounds() {
    10. this.offset = NO_ROW_OFFSET;
    11. this.limit = NO_ROW_LIMIT;
    12. }
    13. public RowBounds(int offset, int limit) {
    14. this.offset = offset;
    15. this.limit = limit;
    16. }
    17. public int getOffset() {
    18. return offset;
    19. }
    20. public int getLimit() {
    21. return limit;
    22. }
    23. }

    对数据库数据进行分页,依靠offset和limit两个参数,表示从第几条开始,取多少条。也就是人们常说的start,limit。

    下面看看Mybatis的如何进行分页的。

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

    Mybatis中使用RowBounds实现分页的大体思路:

    先取出所有数据,然后游标移动到offset位置,循环取limit条数据,然后把剩下的数据舍弃。

    1. private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
    2. throws SQLException {
    3. DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
    4. //跳过RowBounds设置的offset值
    5. skipRows(rsw.getResultSet(), rowBounds);
    6. //判断数据是否小于limit,如果小于limit的话就不断的循环取值
    7. while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    8. ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    9. Object rowValue = getRowValue(rsw, discriminatedResultMap);
    10. storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
    11. }
    12. }
    13. private boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) throws SQLException {
    14. //判断数据是否小于limit,小于返回true
    15. return !context.isStopped() && context.getResultCount() < rowBounds.getLimit();
    16. }
    17. //跳过不需要的行,应该就是rowbounds设置的limit和offset
    18. private void skipRows(ResultSet rs, RowBounds rowBounds) throws SQLException {
    19. if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
    20. if (rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
    21. rs.absolute(rowBounds.getOffset());
    22. }
    23. } else {
    24. //跳过RowBounds中设置的offset条数据,只能逐条滚动到指定位置
    25. for (int i = 0; i < rowBounds.getOffset(); i++) {
    26. rs.next();
    27. }
    28. }
    29. }

    二:RowBounds的使用

    原理:拦截器。

    使用方法:

    RowBounds:在dao.java中的方法中传入RowBounds对象。

    2.1:引入依赖

    1. <dependency>
    2. <groupId>org.mybatis</groupId>
    3. <artifactId>mybatis</artifactId>
    4. <version>3.5.6</version>
    5. </dependency>

    2.2:service层

    1. import org.apache.ibatis.session.RowBounds;
    2. public class UserServiceImpl implements UserService {
    3. @Autowired
    4. private UserDao userDao;
    5. @Override
    6. public Map<String, Object> queryUserList(String currentPage, String pageSize) {
    7. //查询数据总条数
    8. int total = userDao.queryCountUser();
    9. //返回结果集
    10. Map<String,Object> resultMap = new HashMap<String,Object>();
    11. resultMap.put("total", total);
    12. //总页数
    13. int totalpage = (total + Integer.parseInt(pageSize) - 1) / Integer.parseInt(pageSize);
    14. resultMap.put("totalpage", totalpage);
    15. //数据的起始行
    16. int offset = (Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize);
    17. RowBounds rowbounds = new RowBounds(offset, Integer.parseInt(pageSize));
    18. //用户数据集合
    19. List<Map<String, Object>> userList = userDao.queryUserList(rowbounds);
    20. resultMap.put("userList", userList);
    21. return resultMap;
    22. }
    23. }

    2.3:dao层

    1. import org.apache.ibatis.session.RowBounds;
    2. public interface UserDao {
    3. public int queryCountUser(); //查询用户总数
    4. public List<Map<String, Object>> queryUserList(RowBounds rowbounds); //查询用户列表
    5. }

    2.4:mapper.xml

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

    mybatis的拦截器自动操作rowBounds进行分页。

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.test.mapper.UserDao">
    6. <!-- 查询用户总数 -->
    7. <select id="queryCountUser" resultType="java.lang.Integer">
    8. select count(1) from user
    9. </select>
    10. <!-- 查询用户列表 -->
    11. <select id="queryUserList" resultType="java.util.Map">
    12. select * from user
    13. </select>
    14. </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是将所有符合条件的数据全都查询到内存中,然后在内存中对数据进行分页

    如我们查询user表中id>0的数据,然后分页查询sql如下:

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

    但使用RowBounds后,会将id>0的所有数据都加载到内存中,然后跳过offset=3条数据,截取10条数据出来,若id>0的数据有100万,则100w数据都会被加载到内存中,从而造成内存OOM。

    所以当数据量非常大时,一定要慎用RowBounds类。

    以上就是RowBounds分页原理是什么的详细内容,更多关于RowBounds分页原理是什么的资料请关注九品源码其它相关文章!