最近发现对${}与#{}的区别有些模糊,所以重新复习一遍并记下笔记
mybatis#{}与${}的区别
#{}是使用预编译(底层使用preparedStatement调用set方法来赋值),会在参数前后加单引号'
而${}是使用拼接的方式将${}替换为变量
所以mybatis在进行like查询时 "%%"只能使用"%${}%",最后会拼接成"%变量%"
如:select * from t_travelitem where name like "%巴厘岛%"
如果使用"%#{}%"则会被预编译为"%'变量'%"
如select * from t_travelitem where name like "%'巴厘岛'%" (错误的语法)
而"%"#{}"%" 则会被预编译为"%"'变量'"%"如下
select * from t_travelitem where name like "%"'巴厘岛'"%"
"%"${}"%" 则会被拼接为 "%"变量"%"如下 如下
select * from t_travelitem where name like "%"巴厘岛"%" (错误的语法)
为了便于理解,上述sql语句表结构如下
关于#{}与${}的第二个问题
在delete from table where id in()这条sql语句中,只能使用${}不能使用#{}
原因是 使用 ${}是进行拼接 最后sql语句为
delete from table where id in (1,3,5,7,8)
而#{}则会预编译为
delete from table where id in {'1,3,5,7,8'}这样在mysql中只能删掉第一条数据
所以要使用#{}的话就要通过使用动态sql,传输list参数进行遍历
如
<delete id="delete">
delete from table where tid in
<foreach collection="list" item="tid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
最后关于为什么preparedStatement可以防止sql注入可以看看这篇文章