在 mybatis 中,使用 RowBounds 进行分页,非常方便,不需要在 sql 语句中写 limit,即可完成分页功能。但是由于它是在 sql 查询出所有结果的基础上截取数据的,所以在数据量大的sql中并不适用,它更适合在返回数据结果较少的查询中使用

最核心的是在 mapper 接口层,传参时传入 RowBounds(int offset, int limit) 对象,即可完成分页

注意:由于 java 允许的最大整数为 2147483647,所以 limit 能使用的最大整数也是 2147483647,一次性取出大量数据可能引起内存溢出,所以在大数据查询场合慎重使用

mapper 接口层代码如下

List<Book> selectBookByName(Map<String, Object> map, RowBounds rowBounds);

调用如下

List<Book> list = bookMapper.selectBookByName(map, new RowBounds(0, 5));

说明: new RowBounds(0, 5),即第一页,每页取5条数据

测试示例

数据库数据

mapper 接口层

@Mapperpublic interface BookMapper {//添加数据int insert(Book book);//模糊查询List<Book> selectBookByName(Map<String, Object> map, RowBounds rowBounds);}

mapper.xml 文件

<?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.demo.mapper.BookMapper"><resultMap id="BaseResultMap" type="com.demo.bean.Book"><id column="id" property="id" jdbcType="VARCHAR" /><result column="book_name" property="bookName" jdbcType="VARCHAR" /><result column="book_author" property="bookAuthor" jdbcType="VARCHAR" /><result column="create_date" property="createDate" jdbcType="VARCHAR" /><result column="update_date" property="updateDate" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List">book_name as bookName, book_author as bookAuthor,create_date as createDate, update_date as updateDate</sql><insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.demo.bean.Book">insert into book(book_name, book_author, create_date, update_date) values(#{bookName}, #{bookAuthor}, #{createDate}, #{updateDate})</insert><select id="selectBookByName" resultMap="BaseResultMap"><bind name="pattern_bookName" value="'%' + bookName + '%'" /><bind name="pattern_bookAuthor" value="'%' + bookAuthor + '%'" />select * from bookwhere 1 = 1<if test="bookName != null and bookName !=''">and book_name LIKE #{pattern_bookName}</if><if test="bookAuthor != null and bookAuthor !=''">and book_author LIKE #{pattern_bookAuthor}</if></select></mapper>

测试代码


@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootJspApplicationTests {@Autowiredprivate BookMapper bookMapper;@Testpublic void contextLoads() {Book book = new Book();book.setBookName("隋唐演义");book.setBookAuthor("褚人获");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");book.setCreateDate(sdf.format(new Date()));book.setUpdateDate(sdf.format(new Date()));bookMapper.insert(book);System.out.println("返回的主键: "+book.getId());}@Testpublic void query() {Map<String, Object> map = new HashMap<String, Object>();map.put("bookName", "");map.put("bookAuthor", "");List<Book> list = bookMapper.selectBookByName(map, new RowBounds(0, 5));for(Book b : list) {System.out.println(b.getBookName());}}}

运行 query 查询第一页,5 条数据,效果如下

Mybatis提供了一个简单的逻辑分页使用类RowBounds(物理分页当然就是我们在sql语句中指定limit和offset值),在DefaultSqlSession提供的某些查询接口中我们可以看到RowBounds是作为参数用来进行分页的,如下接口:

 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds)

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

逻辑分页的实现原理:

在DefaultResultSetHandler中,逻辑分页会将所有的结果都查询到,然后根据RowBounds中提供的offset和limit值来获取最后的结果,DefaultResultSetHandler实现如下:

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

总结:Mybatis的逻辑分页比较简单,简单来说就是取出所有满足条件的数据,然后舍弃掉前面offset条数据,然后再取剩下的数据的limit条

Mybatis RowBounds 分页原理相关推荐

  1. RowBounds分页原理、RowBounds的坑

    目录 背景说明 一:RowBounds分页原理 二:RowBounds的使用 三:RowBounds的坑 背景说明 项目中经常会使用分页查询,有次使用了RowBounds进行分页,因为很多场景或网上也 ...

  2. Mybatis3.3.x技术内幕(十三):Mybatis之RowBounds分页原理

    2019独角兽企业重金招聘Python工程师标准>>> Mybatis可以通过传递RowBounds对象,来进行数据库数据的分页操作,然而遗憾的是,该分页操作是对ResultSet结 ...

  3. MyBatis的分页原理

    写作目的 最近看到了一篇MyBatis的分页实现原理,文章里描述到使用ThreadLocal,其实想主要想看看ThreadLocal的巧妙使用,并且看一下分页是如何实现的. 源码下载 ChaiRong ...

  4. Mybatis RowBounds分页讲解

    14.RowBounds分页讲解(了解即可) 不在使用SQL实现分页 接口 //分页List<User> getUserRowBounds(); User Mapper.xml <! ...

  5. mybatis RowBounds 分页

    在 mybatis 中,使用 RowBounds 进行分页,非常方便,不需要在 sql 语句中写 limit,即可完成分页功能.但是由于它是在 sql 查询出所有结果的基础上截取数据的,所以在数据量大 ...

  6. mybatis实现分页的几种方式

    本文目录 借助数组进行分页 借助Sql语句进行分页 拦截器分页 RowBounds实现分页 借助数组进行分页 原理:进行数据库查询操作时,获取到数据库中所有满足条件的记录,保存在应用的临时数组中,再通 ...

  7. mybatis常见分页技术和自定义分页原理实战

    文章目录 前言 mybatis简单了解 分页类型 分页方式 1.数组分页 2.数据库分页 3.Rowbounds分页 4.自定义插件分页 自定义分页原理 自定义分页实战 聊下第三方分页插件 pageH ...

  8. mybatis 使用RowBounds 分页

    物理分页和逻辑分页 物理分页:直接从数据库中拿出我们需要的数据,例如在Mysql中使用limit. 逻辑分页:从数据库中拿出所有符合要求的数据,然后再从这些数据中拿到我们需要的分页数据. 优缺点 物理 ...

  9. Mybatis的RowBounds分页

    RowBounds分页 不再使用SQL实现分页 1.接口 List<User> getUserByRowBounds(); 2.mapper.xml <select id=" ...

最新文章

  1. 什么样的人适合学习UI?
  2. 图灵2011年6月书讯【误区】【软件调试修炼之道】即将上市
  3. UI布局分析工具-视图工具(Hierarchy Viewer)
  4. python学习三:列表,元组
  5. 专心做业务,别想不开搞研发
  6. matlab的默认字体_matlab默认字体设置
  7. 转载标明出处用英语_英语原版阅读:At the beach
  8. DataWorks百问百答01:数据同步该用什么资源组
  9. 神作!3万程序员在学,这本深度学习宝典刷爆IT圈!
  10. 35 MM配置-采购-采购订单-设置价格差异的容差限制
  11. 如何把Java的double类型变量保留两位小数
  12. WaitForMultipleObjects函数及原子操作Interlocked系列函数
  13. 《JavaScript高级程序设计(第3版)》阅读总结记录第一章之JavaScript简介
  14. sql 获取日期时分秒_SQL获取系统年月日时分秒 | 学步园
  15. 如何进入进计算机组策略,如何进入组策略?
  16. 电脑串口延迟/缓冲设置方法
  17. Incorrect string value: '\xF0\x9F\x98\x82' for column '' at row 1
  18. Jquery电子签名制作_jSignature
  19. SQL面试问题及回答
  20. iOS毛玻璃磨砂特效

热门文章

  1. wpscan基础用法
  2. WireGuard Easy 安装使用
  3. Mac实用技巧(一)—— 快捷键
  4. 从一个Spring动态代理Bug聊到循环依赖
  5. 嵌入式底层开发为什么选择C语言
  6. Trimble RealWorks处理点云数据(六)之点云数据格式转换
  7. ICDAR 2021竞赛 科学文献分析——表格识别综述部分(剩余部分是文档布局分析)
  8. 【编程马拉松】【004-包含一】
  9. Typora图片上传到CSDN
  10. 【テンプレート】洛谷