前言
在日常工作中我們需要時刻避免被注入攻擊,否則可能你工作就沒了
不安全的演示
使用 ${}
語法時,MyBatis 會直接注入原始字符串,即相當於拼接字符串,因而會導致 SQL 注入
<select id="selectStudentListLike" resultMap="StudentMap">
SELECT * FROM student
WHERE name = ${_parameter}
</select>
List<Student> selectStudentListLike(@Param("name") String name);
數據被全懟出來了
StudentMapper mapper = session.getMapper(StudentMapper.class);
List<Student> code = mapper.selectStudentListLike("'' or 1=1");
System.out.println(code);
避免SQl注入
使用 #{}
語法時,MyBatis 會自動生成 PreparedStatement
<select id="selectStudentListLike" resultMap="StudentMap">
SELECT * FROM student
WHERE name = #{name}
</select>
有時需要進行一些額外邏輯運行,通過 聲明<bind>
元素,並在其value 屬性中添加運算腳本
<select id="selectStudentListLike" resultMap="StudentMap">
<bind name="pattern" value="'%' + name + '%'"/>
SELECT * FROM student
WHERE name LIKE #{pattern}
</select>
concat
<select id="selectStudentListLike" resultMap="StudentMap">
SELECT * FROM student WHERE name LIKE concat ('%', #{name}, '%')
</select>
使用when + 默認值
<select id="selectUserListSortBy" resultMap="StudentMap">
SELECT * FROM student
<choose>
<when test="sortBy == 'name' or sortBy == 'age'">
order by ${sortBy}
</when>
<otherwise>
order by name
</otherwise>
</choose>
</select>