问题现象
带有Limit 的 SQL都默认在后边继续拼接了 limit ?,? 导致SQL语法报错
pageHelper 难道不是必须开启才能使用吗 ?自动拼接什么鬼??
PageHelper.startPage(1,10);
问题分析
经过一番分析,发现是由于加入了配置
supportMethodsArguments 参数,默认是false,
官方介绍
注意: 官方介绍的不是特别清楚,其实这是个自动分页的配置,依据的是入参,如果参数中有pageNum,pageSize分页参数,则会自动分页
参数名称默认取:pageNum,pageSize
参数名称也可以自定义但是需要加配置
以下是测试的结果
使用PageHelper版本 5.1.6
测试时使用的配置(大多项目)
自己写了一个SQL,参数类中有 pageNum,pageSize 参数
当supportMethodsArguments设置为 true 时候默认 启用了分页,并且先执行了count后面的查询也拼接了limit
如果原先SQL中有 limit,并且入参中带有分页参数,则pageHelper会自动执行分页,所以就出现了SQL最后拼接了两个limit导致SQL报错了。
问题解决
supportMethodsArguments参数 默认false ;
解决方案可以将这个配置去掉,或者改为false。将自动根据参数分页配置关闭,在使用的地方手动开启;
公司用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;
-
}