先测试,再说结论
userService.selectStudentByClssIds(10000, "'wzh' or 1=1");
List<StudentEntity> selectStudentByClssIds(@Param("stuId") int stuId, @Param("field") String field);
<select id="selectStudentByClssIds" resultMap="StudentResultMap">SELECTstudent_id, name, age, genderFROM students where name = ${field}</select>
控制台sql执行日志
对比一下,如果是把${field}替换成#{filed}
再玩个更有趣的,如果我们某个sql查询字段需要通过入参确定,如下
<select id="selectStudentByClssIds" resultMap="StudentResultMap">SELECTstudent_id, #{field}, age, genderFROM students;</select>
我们的入参为name,测试结果如下
也就是说这个sql变成了SELECT student_id, 'wzh', age, gender FROM students;
我们把#{field}替换成${filed}再看一下
<select id="selectStudentByClssIds" resultMap="StudentResultMap">SELECTstudent_id, ${field}, age, genderFROM students;</select>
如下,恢复正常了
综上
在 MyBatis 中,#{} 和 ${} 是两种不同的占位符语法,用于处理 SQL 语句中的参数。它们的用途和效果各不相同,不可以混淆
#{} 用于将参数值作为预编译语句的参数。MyBatis 会将该参数值绑定到 SQL 语句中,并自动转换为 SQL 对应类型和进行转义,从而提高安全性,防止 SQL 注入。
${} 用于字符串替换,它直接将传入的参数值插入到 SQL 语句中。MyBatis 不会对使用 ${} 的参数进行处理或转义。 使用 ${} 时,参数直接拼接到 SQL 语句中,因此,如果传入的参数是用户输入的值,没有经过适当的验证和清理,会导致 SQL 注入风险。当您需要动态生成 SQL 语句的部分,如表名、列名等结构时。此时参数不能是用户输入,如,动态指定表名或列名
SELECT * FROM ${tableName} WHERE id = #{id}