工作中用到了这个:
<select id="find" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List" />
FROM mal_merch_allc t
<where>
<if test="s.merchName != null and s.merchName != ''">
<bind name="likeValue1"
value="@com.hbis.ttie.core.mybatis.util.OgnlUtils@toFuzzyValue(s.merchName)"></bind>
and t.merch_name like #{likeValue1,jdbcType=VARCHAR}
</if>
<if test="s.shop != null and s.shop != ''">
and t.shop = #{s.shop,jdbcType=VARCHAR}
</if>
</where>
</select>
总结一下:
在进行模糊查询时,如果使用“${}”拼接字符串,则无法防止 SQL 注入问题。
select * from user where username like '%${name}%'
如果使用字符串拼接函数或连接符号,但不同数据库的拼接函数或连接符号不同。
使用 concat 函数连接字符串,在 MySQL 中,这个函数支持多个参数,但在 Oracle 中只支持两个参数。由于不同数据库之间的语法差异 ,如果更换数据库,有些 SQL 语句可能就需要重写。
select * from user where username like concat ( '1',#{userName},'2' )
针对这种情况,可以使用 bind 标签来避免由于更换数据库带来的一些麻烦。
select * from user
<where>
<if test=" userName != null and userName !='' ">
<bind name="userNameLike" value=" '1'+ userName + '2' " />
and username like #{userNameLike}
</if>
</where>