在 Java 中使用 MyBatis 分页,常见有 3 种方式,从简单到推荐依次如下:
在 SQL 中直接使用 LIMIT(MySQL)或对应数据库分页语法。
<select id="selectByPage" resultType="User">
SELECT * FROM user
LIMIT #{offset}, #{pageSize}
</select>
<select id="countUser" resultType="int">
SELECT COUNT(*) FROM user
</select>
List<User> selectByPage(@Param("offset") int offset,
@Param("pageSize") int pageSize);
int countUser();
int pageNum = 1;
int pageSize = 10;
int offset = (pageNum - 1) * pageSize;
List<User> list = mapper.selectByPage(offset, pageSize);
int total = mapper.countUser();
✅ 优点:最简单、无依赖
❌ 缺点:需手写 count SQL
MyBatis 官方推荐分页插件
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.3</version>
</dependency>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
PageHelper.startPage(1, 10); // 第1页,每页10条
List<User> list = mapper.selectAll();
PageInfo<User> pageInfo = new PageInfo<>(list);
pageInfo.getTotal(); // 总条数
pageInfo.getPages(); // 总页数
pageInfo.getList(); // 当前页数据
✅ 优点:无需改 SQL
✅ 自动 count
✅ 支持多种数据库
❌ 有第三方依赖
如果你用的是 MyBatis-Plus
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
Page<User> page = new Page<>(1, 10);
Page<User> result = userMapper.selectPage(page, null);
result.getRecords(); // 数据
result.getTotal(); // 总数
| 方式 | 依赖 | 是否需写 count | 推荐度 |
|---|---|---|---|
| SQL 分页 | 无 | 是 | ⭐⭐ |
| PageHelper | 有 | 否 | ⭐⭐⭐⭐⭐ |
| MyBatis-Plus | 有 | 否 | ⭐⭐⭐⭐ |
如果你愿意,可以告诉我:
我可以给你 完整示例工程代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。