以下示范如何正确使用pagehelper分页
开发环境
springboot 2.0 + mysql 8.0
一 正确引入pagehelper依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.3</version>
</dependency>
二 在yml或properties中配置pagehelper
page helper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
三 配置 mybatis-config.xml (最不能缺少的一步)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J"/>
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
<plugins>
<!--配置mybatis的分页拦截器!!!!!这步是重点-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>
</configuration>
四 好了,可以正常使用pagehelper分页组件了,逻辑层示例代码如下:
@Override
public TableDataInfo customerListPage(Map<String, Object> params, LoginUser loginUser) {
// 至少要获取以下两个分页参数: currpage当前页,pageSize每页条数
Integer currPage = MapUtils.getInteger(params, "currPage");
Integer pageSize = MapUtils.getInteger(params, "pageSize");
// 如果前端不传,必须要有默认值
if (currPage == null) {
currPage = 1;
}
if (pageSize == null) {
pageSize = 10;
}
// 开始分页
PageHelper.startPage(currPage, pageSize).setReasonable(true);
// 使用 startPage后必须马上接Mapper层的查询接口,且只能识别第一个
List<DatasourceBase> list = datasourceBaseMapper.selectDatasourceBasePage(userLevel, keyword, status, ownUserId, userId, userType);
// 这里我把 list 转化成 输出给前端的格式voList
List<DatasourceBaseVo> voList = list.stream().map(this::getVoByEntity).collect(Collectors.toList());
// 用PageInfo对象接收voList,生成的pageInfo.getList()则为分页后的数据列表
PageInfo<DatasourceBaseVo> pageInfo = new PageInfo<>(voList);
// 由于list经过转化后的voList生成的pageInfo是获取不到查询总数的,再new一个把list放入
PageInfo<DatasourceBase> totalPageInfo = new PageInfo<>(list); // Total必须用list来获取,voList获取不了
// 放入自己封装的对象中,pageInfo.getList()就是分页列表coll,totalPageInfo中能正确获取总条数
return new TableDataInfo(pageInfo.getList(), totalPageInfo.getTotal());
}
五 测试接口
测试时传参获取第1页,每页5条数据:currPage=1,pageSize=5
接口完美通过测试: 查询总条数pageSize与数据库条数一样。分页成功,第一页返回了5条数据。