前言
公司用PageHelper作为Mybatis的分页插件,平时大多数都是用于查询数据库,然后进行分页。最近我想把第三方接口返回的数据进行分页展示,于是也用了PageHelper。
PageHelper:https://pagehelper.github.io/
问题
有的查询语句后面会出现多个Limit 10,eg: select * from tableA limit 10 limit 10
分析
首先看到关于“near limit 10 ”这样的报错就想到了可能是分页的问题,于是检查代码发现:
Page<Object> page = PageHelper.startPage(pageNum, pageSize);
可以看出PageHelper.startPage()方法会在当前线程上下文中设置一个ThreadLocal变量,那么很有可能在这里设置了本地线程变量,但是没有及时的清除,所以导致会多出来limit 10。
但是为什么会没有及时清除呢?PageHelper在哪清除LOCAL_PAGE呢?为什么别的同事的分页查询都正常呢?
后来一想,由于我的数据是调用的第三方的接口,并没有调用doSelectPage()查询。debug看看吧。。。
a.拦截器拦截到查询请求后finally中相关操作
b.发现有个clearPage()
c.这个clearPage()会清空本地线程变量LOCAL_PAGE
只有进行doSelectPage()相关查询时,分页拦截器才会拦截查询请求,并且从ThreadLocal中拿到分页的信息。如果有分页信息,就进行分页查询,最后再把ThreadLocal中的东西清除掉。
至此真相大白,因为我只set了ThreadLocal,而没有调用查询方法,因此拦截器没有remove本地线程变量,导致SQL查询时会多出个limit 10。
解决
自定义一个PageVo存放接口返回数据,这样就避免了setLocalPage()。
PageVo<DataVo> pageVo = new PageVo<>();
pageVo.setResult(...);
pageVo.setTotal(...);
pageVo.setSummary(...);
结论
涉及到ThreadLocal的场景,一定要明白如何使用,什么时候该清除。
扩展
项目中有可能会用到 AopContext.currentProxy(),就是从ThreadLocal中获取代理对象;
前提是要开启注解@EnableAspectJAutoProxy(proxyTargetClass = false,exposeProxy = true)。
/**
* Try to return the current AOP proxy. This method is usable only if the
* calling method has been invoked via AOP, and the AOP framework has been set
* to expose proxies. Otherwise, this method will throw an IllegalStateException.
* @return the current AOP proxy (never returns {@code null})
* @throws IllegalStateException if the proxy cannot be found, because the
* method was invoked outside an AOP invocation context, or because the
* AOP framework has not been configured to expose the proxy
*/
public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(
"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
}
return proxy;
}