bind
引言
在进行模糊查询时,如果使用“${}”拼接字符串,则无法防止 SQL 注入问题。如果使用字符串拼接函数或连接符号,但不同数据库的拼接函数或连接符号不同。
例如 MySQL 的 concat 函数、Oracle 的连接符号“||”,这样 SQL 映射文件就需要根据不同的数据库提供不同的实现,显然比较麻烦,且不利于代码的移植。幸运的是,MyBatis 提供了 元素来解决这一问题。
当然也可以是用concat函数,但是那样写的有一说一不美观
因此我选择用了Bind
用法示例
<select id="getAllAdminUser" resultMap="baseResultMap">
SELECT id,username,nickname,role_id,available
FROM admin_user
<where>
<if test="username != null and ! "".equals(username)">
<bind name="myUsername" value="'%' + username + '%'"/>
username like #{myUsername}
</if>
<if test="nickname != null and ! "".equals(nickname)">
<bind name="myNickname" value="'%' + nickname + '%'"/>
nickname like #{myNickname}
</if>
<if test="role_id != null">
role_id = #{role_id}
</if>
</where>
</select>
优雅