温馨提示×

MyBatis分页查询怎么实现

小亿
85
2023-12-11 22:33:37
栏目: 编程语言

MyBatis提供了两种方式实现分页查询:

  1. RowBounds方式:通过传入RowBounds对象来指定查询的起始行和页大小。例如:
int offset = 0; // 起始行
int limit = 10; // 页大小
RowBounds rowBounds = new RowBounds(offset, limit);

List<User> users = sqlSession.selectList("UserMapper.selectUsers", null, rowBounds);
  1. 使用插件PageHelper:PageHelper是一个开源的MyBatis分页插件,可以简化分页查询的实现。首先在项目中引入PageHelper的依赖:
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>

然后在查询方法前调用PageHelper.startPage()方法来设置分页参数,再通过PageInfo对象获取查询结果和分页信息。例如:

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

int pageNum = 1; // 当前页码
int pageSize = 10; // 页大小

PageHelper.startPage(pageNum, pageSize);
List<User> users = sqlSession.selectList("UserMapper.selectUsers", null);

PageInfo<User> pageInfo = new PageInfo<>(users);
long total = pageInfo.getTotal(); // 总记录数
int pages = pageInfo.getPages(); // 总页数

以上是两种常用的MyBatis分页查询方式,可以根据实际需求选择适合的方式。

0