mybatis if test 之 like
对于mysql 的 like 而言,一般都要用 like concat() 组合,可以防止sql注入
<if test="name!=null and name!=''">
AND name like CONCAT('%',#{name},'%')
</if>
concat()函数
1、功能:将多个字符串连接成一个字符串。
2、语法:concat(str1, str2,…)
返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null。
concat函数:
第一个参数 ,就是'%',其中%后边可以加上一些常量字符比如 / 。
第二参数,基本上就是传递过来的参数 。
第三个参数,是结尾的 '%', %前边可以加一定的常量字符比如 / 。
其他like方式:
//会引起SQL 注入 不推荐
<if test="name!=null and name!=''">
AND name like '%${name}%'
</if>
//因为#{...}解析成sql语句时候,会在变量外侧自动加单引号' ',所以这里 % 需要使用双引号" ",不能使用单引号 ' ',不然会查不到任何结果。
<if test="name!=null and name!=''">
AND name like "%"${name}"%"
</if>