关于RowBounds分页原理、RowBounds的坑记录

 更新时间:2023年04月25日 09:57:10   作者:五月天的尾巴  
这篇文章主要介绍了关于RowBounds分页原理、RowBounds的坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

背景说明

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

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

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

如我们写的sql语句:

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源码如下:

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;
  }

}

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

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

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

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

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

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);
//判断数据是否小于limit,如果小于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 boolean shouldProcessMoreRows(ResultContext<?> context, RowBounds rowBounds) throws SQLException {
    //判断数据是否小于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条数据,只能逐条滚动到指定位置
      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) {
        //查询数据总条数
        int total = userDao.queryCountUser();
        //返回结果集
        Map<String,Object> resultMap = new HashMap<String,Object>();
        
        resultMap.put("total", total);
        //总页数
        int totalpage = (total + Integer.parseInt(pageSize) - 1) / Integer.parseInt(pageSize);
        resultMap.put("totalpage", totalpage);
        
        //数据的起始行
        int offset = (Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize);
        RowBounds rowbounds = new RowBounds(offset, Integer.parseInt(pageSize));
        //用户数据集合
        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();       //查询用户总数
    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">
    
    <!-- 查询用户总数 -->
    <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:
— Error querying database. Cause: java.sql.SQLException: Java heap space
— The error may exist in com/test/mapper/InfoRecordMapper.java (best guess)
– The error may involve com.test.mapper.InfoRecordMapper.selectByExampleAndRowBounds-Inline
— The error occurred while setting parameters

RowBounds是将所有符合条件的数据全都查询到内存中,然后在内存中对数据进行分页

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

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

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

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java日常练习题,每天进步一点点(35)

    Java日常练习题,每天进步一点点(35)

    下面小编就为大家带来一篇Java基础的几道练习题(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望可以帮到你
    2021-07-07
  • 收集的一些常用java正则表达式

    收集的一些常用java正则表达式

    收集的一些常用java正则表达式,需要的朋友可以参考一下
    2013-02-02
  • File的API和常用方法详解_动力节点Java学院整理

    File的API和常用方法详解_动力节点Java学院整理

    这篇文章主要为大家详细介绍了File的API和常用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • 为何修改equals方法时还要重写hashcode方法的原因分析

    为何修改equals方法时还要重写hashcode方法的原因分析

    这篇文章主要介绍了为何修改equals方法时还要重写hashcode方法的原因分析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Springboot2 集成 druid 加密数据库密码的配置方法

    Springboot2 集成 druid 加密数据库密码的配置方法

    这篇文章给大家介绍Springboot2 集成 druid 加密数据库密码的配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2021-07-07
  • java实现图像转码为字符画的方法

    java实现图像转码为字符画的方法

    这篇文章主要为大家详细介绍了java实现图像转码为字符画的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • 一文详解Java的饿汉和懒汉设计模式

    一文详解Java的饿汉和懒汉设计模式

    这篇文章主要为大家详细介绍了Java设计模式中的的饿汉模式和懒汉模式,文中的示例代码讲解详细,对我们学习Java有一定的帮助,需要的可以参考一下
    2022-12-12
  • SpringBoot单点登录实现过程详细分析

    SpringBoot单点登录实现过程详细分析

    这篇文章主要介绍了SpringBoot单点登录实现过程,单点登录英文全称Single Sign On,简称就是SSO。它的解释是:在多个应用系统中,只需要登录一次,就可以访问其他相互信任的应用系统
    2022-12-12
  • Java Filter 过滤器详细介绍及实例代码

    Java Filter 过滤器详细介绍及实例代码

    Filter也称之为过滤器,它是Servlet技术中最实用的技术,本文章WEB开发人员通过Filter技术,对web服务器管理的所有web资源进行拦截,从而实现一些特殊的功能,本文章将向大家介绍Java 中的 Filter 过滤器,需要的朋友可以参考一下
    2016-12-12
  • SpringBoot org.springframework.beans.factory.UnsatisfiedDependencyException依赖注入异常

    SpringBoot org.springframework.beans.factory.Unsatisfie

    本文主要介绍了SpringBoot org.springframework.beans.factory.UnsatisfiedDependencyException依赖注入异常,文中通过示例代码介绍的很详细,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02

最新评论