mybatis中的#和$的区别:

1、#将传入的数据都当成一个字符串,会对主动传入的数据加一个双引号。
如:where username=#{username},如果传入的值是111,那么解析成sql时的值为where username="111", 如果传入的值是id,则解析成的sql为where username="id". 
2、$将传入的数据间接显示生成在sql中。
如:where username=${username},如果传入的值是111,那么解析成sql时的值为where username=111;

3、针对下面的sql,如果传入的值是;drop table user;,

那么第一条用#{}的sql解析为:select id, username, password, role from user where username=";drop table user;"

那么第二条用${}的sql解析为:select id, username, password, role from user where username=;drop table user;

这时候曾经sql注入了。

3、#形式可能很大水平避免sql注入,$形式无奈避免Sql注入。
4、$形式个别用于传入数据库对象,例如传入表名和列名,还有排序时应用order by动静参数时须要应用$ ,ORDER BY ${columnName}
5、个别能用#的就别用$,若不得不应用“${xxx}”这样的参数,要手工地做好过滤工作,来避免sql注入攻打。
6、在MyBatis中,“${xxx}”这样格局的参数会直接参与SQL编译,从而不能防止注入攻打。但波及到动静表名和列名时,只能应用“${xxx}”这样的参数格局。所以,这样的参数须要咱们在代码中手工进行解决来避免注入。
【论断】在编写MyBatis的映射语句时,尽量采纳“#{xxx}”这样的格局。若不得不应用“${xxx}”这样的参数,要手工地做好过滤工作,来避免SQL注入攻打。