PageHelper.startPage()使用问题:自动添加多余的limit,以及利用PageInfo和Page手动分页
问题描述
在工作中使用PageHelper.startPage()方法来让mybait为我们自动设置分页的pageNum,pageSize,但是有时候会出现自动为我们添加到了不需要分页的查询sql中,导致以下问题:
- 查询报错,提示如下信息,sql没有问题,是自动添加了多余的LIMIT ?,并且只是偶然发生;
- 查询的结果一页应显示10条,实则显示5条;
使用规范
针对以上出现的情况,主要原因是.startPage()使用不当,参考相关说明文档后,建议使用方法为:Mapper接口方式的调用,但是必须紧跟.startPage()方法;
<pre class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" style="margin: 0px; padding: 0px; overflow: scroll; color: rgb(17, 17, 17); font-size: 13px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"> PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1);</pre>
问题原因
底层主要是通过将pageNum,pageSize放入ThreadLocal,
<pre class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" style="margin: 0px; padding: 0px; overflow: scroll; color: rgb(17, 17, 17); font-size: 13px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"> protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();</pre>
但是在执行完.startPage()后,没有查询数据库操作,并且此次查询请求响应结束,线程空闲时,又有新的别的查询请求进来,此时线程复用,mybaits通过自身的拦截器,导致给新的查询自动添加了limit?,?,从而报错
解决方案
因为项目中是查询多次分类的结果后,需要对list进行分页,此种情况,结合PageInfo和Page进行手动分页,通过以下方法实现
<pre class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" style="margin: 0px; padding: 0px; overflow: scroll; color: rgb(17, 17, 17); font-size: 13px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">
/**
- pagehelper 手动分页
- @param currentPage 当前页
- @param pageSize
- @param list
- @param <T>
- @return
*/
public static <T> PageInfo<T> getPageInfo(int currentPage, int pageSize, List<T> list) {
int total = list.size();
if (total > pageSize) {
int toIndex = pageSize * currentPage;
if (toIndex > total) {
toIndex = total;
}
list = list.subList(pageSize * (currentPage - 1), toIndex);
}
Page<T> page = new Page<>(currentPage, pageSize);
page.addAll(list);
page.setPages((total + pageSize - 1) / pageSize);
page.setTotal(total);
PageInfo<T> pageInfo = new PageInfo<>(page);
return pageInfo;
}</pre>