mybatis的in查询使用string之#与$

244 阅读1分钟

问题

@Select(select * from user where id in(#{param}))
List<User> getUserById(String param)

此时代码执行结果查询出来为空,但是数据库查询是有值。

分析

这一定有蹊跷,思前想后不对劲,果然太年轻了,这跟 # 与 $ 有关系。

#是预编译处理,MyBatis在处理#{param}时,它会将sql中的#{param}替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,即上述原本是要表达 selcet * from user where id in (1,3,4) 会变成selcet * from user where id in ('1,3,4')这样就能看出问题了吧。

但是如果用的是${param} 这时候就是字符串替换了,即selcet * from user where id in (1,3,4) 这时候就能保证结果是正确的了。

但是一般${param}的方式会有sql注入的问题,所以在使用时还是要谨慎处理。

解决方案

@Select(select * from user where id in(${param}))
List<User> getUserById(String param)