参考链接:
Mabatis中#{}和${}的区别
在mybatis的sql标签中,有属性:parameterType
其描述是:将要传入语句的参数的完全限定类名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器推断出具体传入语句的参数,默认值为未设置(unset)。
parameterType决定了输入参数的类型,而当该类型为简单类型(8个基本类型+String)和对象类型时,两个取值符号如何使用?
1、parameterType为简单类型
1.1 使用方式
#{任意值}
${value} ,其中的标识符只能是value,取其他值
<select id="queryPersonById" parameterType="int" resultType="person">
select * from person where id=#{xxx}
</select>
<select id="queryPersonById" parameterType="int" resultType="person">
select * from person where id=${value}
</select>
1.2 适用范围
#{} 自动给String类型加上’’ ,发生了自动类型转换,适合参数传值
${} 字符替换,原样输出,适合于 动态排序(动态字段)
在mysql中,对于int类型参数,我们可以看到,添加引号和没引号查询的结果是相同的。
mysql> select * from person where id=1001;
mysql> select * from person where id="1001";
而对于String类型的参数,没加引号会报错。
select * from person where name=zs;
ERROR 1054 (42S22): Unknown column 'zs' in 'where clause'
select * from person where name="zs";
由此可以知道,在实际查询varchar类型的字段时,#{}正常使用即可,而${}因为是字符替换,对于使用字符串类型参数时需要手动添加引号。由此也可知道,${}不适合于参数传值。
<select id="queryPersonByName" parameterType="String" resultType="person">
select * from person where name="${value}"
</select>
然而,在动态排序中,使用 #{} 时, 在查询的结果中,未能正确排序,原因是 #{colume} 被解析成为一个字符串,导致排序失败。
<select id="queryPersonOrderByColumn" parameterType="String" resultType="person">
select * from person order by #{colume} desc
</select>
而使用 ${} 进行排序时,结果正常。
<select id="queryPersonOrderByColumn" parameterType="String" resultType="person">
select * from person order by ${value} desc
</select>
1.3 是否防止SQL注入
#{}可以防止SQL注入
${}不防止
2、parameterType为对象类型
2.1 使用方式
#{属性名}
${属性名}
<!-- 输入参数为对象 -->
<select id="queryPersonByIdWithObj" parameterType="Person" resultType="person">
select * from person where id=${id}
</select>
2.2 相同点
两者均支持级联属性,也就是在一个类中存在对象属性时(嵌套),也能引用该对象属性中的属性。
#{对象属性.成员}
${对象属性.成员}
3、parameterType为HashMap类型
用map中key的值 匹配 占位符#{},如果匹配成功 就用map的value替换占位符
test.java
HashMap<String, Object> personMap = new HashMap<String, Object>();
personMap.put("map_id", 117);
personMap.put("map_name", "ls");
personMapper.java
List<Person> queryPersonWithHashMap(HashMap<String, Object> hashMap);
personMapper.xml
<select id="queryPersonWithHashMap" parameterType="HashMap" resultType="person">
select * from person where id=#{map_id} or name=#{map_name}
</select>