Mybatis-PageHelper分页参数附加到未分页查询语句
报错信息
limit参数加到了不需要分页的查询语句上,并且确定此查询没有在分页中使用。
原因
PageHelper的不正确使用。PageHelper后没有紧接着查询,导致分页参数所在线程的ThreadLocal 参数没有被清除,作用在下次同个线程的请求上。
PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
只要保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
参考:https://blog.csdn.net/qq_34988304/article/details/90030134
验证
在有问题的PageHelper使用后打印当前线程名、线程id,在另一个有查询数据库没有分页需求的controller中打印当前线程名、线程id
# 有问题的controller请求所在线程
当前线程名字:http-nio-8080-exec-1 当前线程的优先级别为:5 ID:35
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-3 当前线程的优先级别为:5 ID:37
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-4 当前线程的优先级别为:5 ID:38
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-5 当前线程的优先级别为:5 ID:39
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-6 当前线程的优先级别为:5 ID:40
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-7 当前线程的优先级别为:5 ID:41
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-8 当前线程的优先级别为:5 ID:42
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-9 当前线程的优先级别为:5 ID:43
# 省略其他日志信息
当前线程名字:http-nio-8080-exec-10 当前线程的优先级别为:5 ID:44
# 省略其他日志信息,使用同一线程时报错
当前线程名字:http-nio-8080-exec-1 当前线程的优先级别为:5 ID:35
2021-11-18 19:42:59.898 ERROR com.baidu.itest.web.aop.LogAspect [59][http-nio-8080-exec-1] [Controller Error][controller=Response com.baidu.itest.web.controller.workbench.TodoController.getTodoConfirmations(HttpServletRequest,Integer,Integer)][execute_time=59][param=]error=
org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 10' at line 11
### The error may exist in file [/Users/wangye25/workspace/baidu/itest/itest-online/itest-dao/target/classes/mapper/ItestStatusMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT id FROM itest_status WHERE label = ? AND type = ? ORDER BY rank ASC LIMIT 1; LIMIT ?
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 10' at line 11
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 10' at line 11
... 省略下面的报错
可以看到,PageHelper使用错误的请求所在线程的id为35,当正常的请求使用到同一时报错。