java PageHelper用法、怎么使用
文章目录
MyBatis 分页插件 PageHelper 使用指南
在使用 MyBatis 进行分页查询时,有多种方法可供选择。本文将介绍几种常见的分页方式,并推荐最优的使用方法。
第一种:使用 RowBounds 方式
List<Country> list = sqlSession.selectList("x.y.selectIf", null, new RowBounds(0, 10));
这种方式使用 MyBatis 提供的 RowBounds
类进行分页。但在大数据量时,效率较低,不推荐使用。
第二种:使用 Mapper 接口方式(推荐)
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1);
通过 PageHelper.startPage
方法设置分页参数,然后调用 Mapper 接口方法查询数据。这种方式简洁明了,推荐使用。
第三种:使用 Mapper 接口方式(推荐)
PageHelper.offsetPage(1, 10);
List<Country> list = countryMapper.selectIf(1);
与第二种方式类似,但使用 PageHelper.offsetPage
设置分页参数,同样推荐使用。
第四种:参数方法调用
// 定义 Mapper 接口
public interface CountryMapper {
List<Country> selectByPageNumSize(
@Param("user") User user,
@Param("pageNum") int pageNum,
@Param("pageSize") int pageSize);
}
// 配置 supportMethodsArguments=true
List<Country> list = countryMapper.selectByPageNumSize(user, 1, 10);
这种方式通过在 Mapper 接口中传递分页参数实现分页查询,简化了 XML 配置。
第五种:参数对象
public class User {
private Integer pageNum;
private Integer pageSize;
// 其他字段
}
// 定义 Mapper 接口
public interface CountryMapper {
List<Country> selectByPageNumSize(User user);
}
// 当 User 对象中的 pageNum 和 pageSize 不为 null 时,会自动分页
List<Country> list = countryMapper.selectByPageNumSize(user);
将分页参数封装在对象中,只需传递对象即可实现分页,简化了方法调用。
第六种:使用 ISelect 接口方式
// JDK 6, 7 用法,创建接口
Page<Country> page = PageHelper.startPage(1, 10).doSelectPage(new ISelect() {
@Override
public void doSelect() {
countryMapper.selectGroupBy();
}
});
// JDK 8 lambda 用法
Page<Country> page = PageHelper.startPage(1, 10).doSelectPage(() -> countryMapper.selectGroupBy());
// 返回 PageInfo 对象
PageInfo<Country> pageInfo = PageHelper.startPage(1, 10).doSelectPageInfo(new ISelect() {
@Override
public void doSelect() {
countryMapper.selectGroupBy();
}
});
// lambda 用法
PageInfo<Country> pageInfo = PageHelper.startPage(1, 10).doSelectPageInfo(() -> countryMapper.selectGroupBy());
// count 查询,返回查询结果的总数
long total = PageHelper.count(new ISelect() {
@Override
public void doSelect() {
countryMapper.selectLike(country);
}
});
// lambda 用法
total = PageHelper.count(() -> countryMapper.selectLike(country));
这种方式使用 ISelect
接口或 lambda 表达式进行分页查询,代码更加简洁,适合高级用法。
总结
在 MyBatis 中进行分页查询时,推荐使用 PageHelper.startPage
方法与 Mapper 接口结合的方式。这种方式不仅简洁,还能高效地处理大数据量分页需求。如果有更复杂的需求,可以考虑使用参数对象或 ISelect
接口方式。通过选择合适的分页方式,可以大大提升开发效率和代码可读性。