使用步骤
- 1.引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.2</version>
</dependency>
- 2.查询操作前设置pageHelper分页语句即可
PageHelper.startPage(pageNow,pageSize);
此句作用,在mysql中,相当于查询子句执行完,动态的拼加了 limit 语句
eg.
public List<Category> findCategorys(Integer pageNow, Integer pageSize) {
//核心语句1 设置分页
PageHelper.startPage(pageNow,pageSize);
//设置条件
CategoryExample example = new CategoryExample();
//执行查询
List<Category> categories = categoryMapper.selectByExample(example);
return categories;
}
扩展
如果单纯的查询结果满不足不了业务需求,例如需要获取总记录数、总页数时,可以引入pageHelper封装的PagInfo对象,将我们查询的到的集合,包装为一个内容丰富的信息对象。
PageInfo<T> pageInfo = new PageInfo<>(查询结果集合);
eg.
public PageInfo<Category> findCategorys(Integer pageNow, Integer pageSize) {
//核心语句1 设置分页
PageHelper.startPage(pageNow,pageSize);
//设置条件
CategoryExample example = new CategoryExample();
//执行查询
List<Category> categories = categoryMapper.selectByExample(example);
//核心语句2 封装pagInfo对象,里面包含当前页,总页数,总记录数...
PageInfo<Category> pageInfo= new PageInfo<>(categories);
return pageInfo;
}