记一次 PageHelper 使用碰到的坑
昨天晚上在新项目中使用 pageHelper 插件时,发下不管怎么查询查询的结果都是查询全部,分页设置并没有生效
代码如下:
// 设置分页参数
PageHelper.startPage(page.getPageNum(),page.getPageSize());
// 运行查询语句
List<AuthUser> list = authUserMapper.list(account);
// 对查询结果进行分页
PageInfo<AuthUser> pageInfo = new PageInfo<>(list);
排查了半天,没有发现有错误的地方,跟进源码发现在进行分页处理时,代码将查询得到的 list 作为 collection 来处理了。
public PageInfo(List<T> list, int navigatePages) {
if (list instanceof Page) {
Page page = (Page) list;
this.pageNum = page.getPageNum();
this.pageSize = page.getPageSize();
this.orderBy = page.getOrderBy();
this.pages = page.getPages();
this.list = page;
this.size = page.size();
this.total = page.getTotal();
//由于结果是>startRow的,所以实际的需要+1
if (this.size == 0) {
this.startRow = 0;
this.endRow = 0;
} else {
this.startRow = page.getStartRow() + 1;
//计算实际的endRow(最后一页的时候特殊)
this.endRow = this.startRow - 1 + this.size;
}
} else if (list instanceof Collection) {
this.pageNum = 1;
this.pageSize = list.size();
this.pages = 1;
this.list = list;
this.size = list.size();
this.total = list.size();
this.startRow = 0;
this.endRow = list.size() > 0 ? list.size() - 1 : 0;
}
if (list instanceof Collection) {
this.navigatePages = navigatePages;
//计算导航页
calcNavigatepageNums();
//计算前后页,第一页,最后一页
calcPage();
//判断页面边界
judgePageBoudary();
}
}
debug 发现 list 此时是 ArrayList,并不是源码中需要的 Page。
继续跟进源码发现插件并没有注入到项目中,排查了配置发现没有进行配置。在 xml 中进行配置后再进行 debug,list 已经是 Page 类型的了
spring 项目中配置:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper"/>
<!--<bean class="com.yanchengtech.ft.common.interceptor.LogTimeInterceptor"/>-->
</array>
</property>
</bean>
在 springboot 项目中需要有两个依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.3</version>
</dependency>