MyBatis中 #{} 和 ${} 的区别
在MyBatis中,我们通常使用 #{}
参数语法,这种情况下,MyBatis会创建 PreparedStatement
参数占位符,并通过占位符安全地设置参数。这种语法更安全、迅速,是首选的做法,但是如果有时候想在SQL语句中直接插入一个不转义的字符串,则需要使用 ${}
语法。
二者区别
-
#会对输入的值做字符串化处理,自动用双引号包裹后生成语句。例如,SQL语句为
where user name = #{user name}
,如果传入值为111,则生成的语句为where user name = ”111“
,如果传入值为ID,则生成的语句为where user name = ”ID“
。 -
$将传入值直接展示、生成SQL语句。例如,SQL语句为
where user name = ${user name}
,如果传入值为111,则生成的语句为where user name = 111
-
如果对于上述的SQL,如果传入的值为 ;drop table user;
则用#生成的语句为:
select id, username, password, role from user where username ="; drop table user;”
而用$生成的语句为:
select id, username, password, role from user where username =; drop table user;
,这种情况下,会发生SQL注入漏洞。因此,#可以在最大程度下防止SQL注入,而$无法防范SQL注入风险。
-
在我们需要动态生成SQL语句,传入列名、表名的情况下,只能使用$传入。
结论
尽可能使用 #{}
,如果处于动态SQL语句的原因使用 ${}
,必须做好SQL防注入的风险规避。