mybatis bind标签

开门见山的说,平时写模糊查询,一直用${name},例如:

select * from table where name like '%${name}%'

后来知道了,这样写可能会引发sql注入,于是乎,要用到这样一个标签 bind,经过改正上面的sql可以变成

<bind name="bindeName" value="'%'+name+'%'"/>
SELECT * FROM table where name like #{bindeName}

大致就上面这个意思,不要在意一些细节。就相当于在bind标签中的value值中,把需要的字符拼接好,然后用name中的值去代替拼接好的参数。

这个用法同样用于一些防止更换数据库的sql中。例如:

concat标签,在mysql中,可以拼接多个字符,但是如果有一天,你的数据库突然变成了oracle,concat就会报错了,因为它只能接受两个参数。

这个时候,bind同样适用,如下:

开始的时候:

<if test=” userName != null and userName ! = ””>
  and username like concat ( '1',#{userName},'2'</if>

可以改成:

<if test=” userName != null and userName !=””> 
  <bind name= " userNameLike ” value = ”'1'+ userName + '2'”/>
  and username like #{userNameLike} 
</if>  

 

 

posted @ 2019-11-18 09:57  半瓶假酒  阅读(4312)  评论(2编辑  收藏  举报