最近做的项目,使用了Spring的PageHelper插件,发现了一个奇怪的问题,经常会给SQL无缘无故的增加Limit语句,经过调查,发现原因是没有安全的使用PageHelper插件,我们先来看一个例子:
PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());
PageInfo list = null;
if (condition.getCustomerIdListForUser() != null && condition.getCustomerIdListForUser().size() > 0) {
list = new PageInfo<>(ocs010Mapper.findOrderList(condition)); //分页查询语句
} else {
list = new PageInfo<>(new ArrayList());
list.setPageNum(0);
list.setPageSize(1);
list.setTotal(0);
}
在这个例子中,PageHelper.startPage就属于明显的不安全调用,因为PageHelper的原理是,在PageHelper.startPage调用时,会给全局对象LOCAL_PAGE设值,然后通过Spring的拦截器拦截每个SQL语句,如果LOCAL_PAGE有值,则给该SQL增加Limit,并调用clearPage方法清除LOCAL_PAGE的值;
但是上面的代码,其分页查询语句有可能因为if的条件的不满足没有执行,所以在程序执行结束时,PageHelper.startPage已经执行,LOCAL_PAGE的值已经设置
当线程池再次分配该线程执行其他程序时,可能会在该程序的第一个SQL上增加了Limit语句。
解决该问题的方法是,要绝对保证PageHelper.startPage和分页查询语句之间不要有任何其他语句,或者在程序结束时增加PageHelper.clearPage();的调用,例:
PageInfo list = null;
if (condition.getCustomerIdListForUser() != null && condition.getCustomerIdListForUser().size() > 0) {
PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());
list = new PageInfo<>(ocs010Mapper.findOrderList(condition));//分页查询语句
} else {
list = new PageInfo<>(new ArrayList());
list.setPageNum(0);
list.setPageSize(1);
list.setTotal(0);
}
或者
PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());
PageInfo list = null;
if (condition.getCustomerIdListForUser() != null && condition.getCustomerIdListForUser().size() > 0) {
list = new PageInfo<>(ocs010Mapper.findOrderList(condition));
} else {
list = new PageInfo<>(new ArrayList());
list.setPageNum(0);
list.setPageSize(1);
list.setTotal(0);
}
PageHelper.clearPage();