1、#{}将传入的数据当作一个字符串,会对传入的数据加上一个双引号。
比如,
select * from student where student_name = #{studentName}
如果传入的值为xiaoming,那么解析成sql的值为student_name="xiaoming"。
2、${}将传入的数据直接显示生成在sql中。
如 :
select ${fieldNmae} from student where student_age = 18
此时,传入的参数作为要查询的字段,如果传入的值为student_name,则解析成的sql为:
select student_name from student where age = 18
3、#{}方式能够很大程度上防止sql注入。
4、${}无法防止sql注入。
5、${}方式一般用于传入数据库对象,例如列表和表名。
6、由于#{}方式具有更高的安全行,所以能用#{}的地方尽量不要使用${}。
7、Mybatis排序时使用order by动态参数时需要注意,用${}而不是#{}。
动态sql时mybatis的主要特性之一,在mapper中定义的参数传到xml中之后,在查询之前mybatis会对其进行动态解析。mybatis提供了两种支持动态sql的语法:#{}以及${}。
比如,下面两个语句,如果参数name值为:xioming,则这两种方式无任何区别;
select * from student where name = #{name}
select * from student where name = ${name}
其解析之后的结果均为:
select * from student where name = "xiaoming"
#{}和${}的不同之处在于预编译中的处理。#{}在预处理时,会把参数部分用一个占位符?代替,变成如下的sql语句:
select * from student where name = ?
而${}只是简单的字符串替换,在动态解析阶段,该sql语句会被解析成:
select * from student where name = "xiaomng"
#{}的参数替换发生在DBMS中,而${}则发生在动态解析过程中。