零散知识篇--mybatis--${}与#{}的区别

#{}特点

举个例子,我们看如下mapper文件: 

<select id="selectAll" resultType="com.test.People">
   select id, name, age from people where id = #{id}
</select>

实际执行的时候,会执行如下代码

String sql = "select id,name,age from people where id =?";
PreparsedStatement ps = conn.preparseStatement(sql);
ps.setint(1, 1005)

可以看到,实际sql语句中的id值会用?代替,后通过PreparsedStatement 执行,最后再用值替换掉?。所以,使用#{}有如下特点:

  • 可以防止sql注入
  • 外部执行时看不到值,会比较安全

另外还有一点

  • 执行的效率会比较高

${}特点

同样的mapper文件,如果我们把# 换成$符号,执行效果是一样的,但会有很多隐患。因为它执行sql语句的逻辑就是字符串拼接,比如按照上面的mapper文件,如果我们使用$符号,那么它其实就是在执行如下语句:

String sql = "select id,name,age from people where id" + "1005";

所以,这样可能会造成sql注入,同时,外部执行时会暴露值。且执行效率也不高。

那么,$就一无是处,平时就用不到了吗,也不是的。我们一般在替换列或表名的时候使用$符号。比如:

<select id="selectAll" resultType="com.test.People">
   select id, name, age from people order by #{name}
</select>
posted @ 2022-02-11 17:09  盲从者列表  阅读(52)  评论(0)    收藏  举报