Mybatis RowBounds 分页原理

在 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 接口层



@Mapper

public 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 book

where 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)

@SpringBootTest

public class SpringbootJspApplicationTests {


@Autowired

private BookMapper bookMapper;


@Test

public 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());

}


@Test

public 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.  
  3. /* 默认offset是0**/

  4. public static final int NO_ROW_OFFSET = 0;

  5.  
  6. /* 默认Limit是int的最大值,因此它使用的是逻辑分页**/

  7. public static final int NO_ROW_LIMIT = Integer.MAX_VALUE;

  8. public static final RowBounds DEFAULT = new RowBounds();

  9.  
  10. private int offset;

  11. private int limit;

  12.  
  13. public RowBounds() {

  14. this.offset = NO_ROW_OFFSET;

  15. this.limit = NO_ROW_LIMIT;

  16. }

  17.  
  18. public RowBounds(int offset, int limit) {

  19. this.offset = offset;

  20. this.limit = limit;

  21. }

  22.  
  23. public int getOffset() {

  24. return offset;

  25. }

  26.  
  27. public int getLimit() {

  28. return limit;

  29. }

  30.  
  31. }

逻辑分页的实现原理:

 

在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条

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值