首先看一下下面这两个sql语句的区别:
<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap"> select id, username, password, role from user where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR} </select> <select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap"> select id, username, password, role from user where username = ${username,jdbcType=VARCHAR} and password = ${password,jdbcType=VARCHAR} </select>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;
注意:使用#{}预编译时把值用 '' 引号包裹起来就变成了一个字符串的值,但是使用${}时,它是没有引号包裹,就是直接填充的,当输入 ;drop table user;时。实际是两条SQL语句了,这时候已经sql注入了。
3、#方式能够很大程度防止sql注入,$方式无法防止Sql注入。 4、$方式一般用于传入数据库对象,例如传入表名和列名,还有排序时使用order by动态参数时需要使用$ ,ORDER BY ${columnName} 5、一般能用#的就别用$,若不得不使用“${xxx}”这样的参数,要手工地做好过滤工作,来防止sql注入攻击。 6、在MyBatis中,“${xxx}”这样格式的参数会直接参与SQL编译,从而不能避免注入攻击。但涉及到动态表名和列名时,只能使用“${xxx}”这样的参数格式。所以,这样的参数需要我们在代码中手工进行处理来防止注入。
【总结】在编写MyBatis的映射语句时,尽量采用“#{xxx}”这样的格式。若不得不使用“${xxx}”这样的参数,要手工地做好过滤工作,来防止SQL注入攻击。