问题复现
代码:
//测试controller。
@RestController
@RequestMapping("/pageHelperTest")
public class PageHelperTestController {
@Autowired
TestMapper testMapper;
@RequestMapping("/list/{pageNo}")
public Pagination search(@PathVariable("pageNo") int pageNo) {
Wrapper wrapper = new EntityWrapper();
PageHelper.startPage(pageNo, 10);
List<TestEntity> testEntityList = testMapper.selectList(wrapper);
return PageHelper.getPagination();
}
@RequestMapping("/listTwo")
public List<TestEntity> search2{
Wrapper wrapper = new EntityWrapper();
wrapper.eq("id", "111111");//只能查到一条
List<TestEntity> testEntityList = testMapper.selectList(wrapper);
return testEntityList;
}
}
测试:
- 浏览器访问“/pageHelperTest/listTwo”,结果:可以查到一条数据
- 浏览器访问“/pageHelperTest/list/2”,将PageHelper页码设置成2,结果:分页信息。
- 再次请求“/pageHelperTest/listTwo”,结果:可能会查到一条数据,也可能返回空结果。
问题分析
为什么会有空结果出现?
-
网络异常?本地调用,不太可能网络问题。
-
数据被删除?数据被删除了就会一直为空,但是却不是这样。
-
灵异事件?阿弥陀佛!
-
PageHelper内部机制问题?只可能是这个了,源码查一下。
PageHelper源码实现:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.baomidou.mybatisplus.plugins.pagination;
import com.baomidou.mybatisplus.exceptions.MybatisPlusException;
public class PageHelper {
private static final ThreadLocal<Pagination> LOCAL_PAGE = new ThreadLocal();
public PageHelper() {
}
public static long getTotal() {
if (isPageable()) {
return ((Pagination)LOCAL_PAGE.get()).getTotal();
} else {
throw new MybatisPlusException("The current thread does not start paging. Please call before PageHelper.startPage");
}
}
public static int offsetCurrent(int current, int size) {
return current > 0 ? (current - 1) * size : 0;
}
public static int offsetCurrent(Pagination pagination) {
return null == pagination ? 0 : offsetCurrent(pagination.getCurrent(), pagination.getSize());
}
public static long freeTotal() {
long total = getTotal();
remove();
return total;
}
public static Pagination getPagination() {
return (Pagination)LOCAL_PAGE.get();
}
public static void setPagination(Pagination page) {
LOCAL_PAGE.set(page);
}
public static void startPage(int current, int size) {
LOCAL_PAGE.set(new Pagination(current, size));
}
public static boolean isPageable() {
return LOCAL_PAGE.get() != null;
}
public static void remove() {
LOCAL_PAGE.remove();
}
}
startPage方法把分页信息Pagination存放到了ThreadLocal里。ThreadLocal是线程保护的,作用域只限于当前线程。
难道是接收网页请求的servlet线程池内一个线程被污染了,但是它还一直存活在线程池。当新的请求进来,如果是这个线程处理则会使用错误的分页信息,否则就是正确的分页信息?所以才会出现时有时无的现象?
有了,那我们就不断请求“/pageHelperTest/list/2”,污染掉线程池大部分线程。
果然,多次污染线程后,再请求“/pageHelperTest/listTwo”均返回空结果。
解决方案
- 使用PageHelper.remove();移除分页信息。
- 单表查询使用mybatis-plus自带的分页方法selectPage;
- 使用自定义SQL时,在Mapper的方法的第一个形参设置为Page。
//Mapper定义 List<Object> selectBySql(Page<Object> page, Map<String, Object> paramMap);
//service实现 public Page<Object> selectBySql(int pageNo, int pageSize, Map<String, Object> paramMap) { Page<Object> page = new Page<Object>(pageNo, pageSize); return page.setRecords(mapper.selectBySql(page, paramMap)); }
完成!如有问题,欢迎指正。