myabtis模糊查询对 % _ \ [ ]特殊符号的处理
java工具类:
/**
* @title: EscapeUtil
* @description: mysql的模糊查询时特殊字符转义工具类
* @date 2019/11/2016:12
*/
public class EscapeUtil {
/**
* mysql的模糊查询时特殊字符转义
*
* @param str 需要转换的字符串
* @return 返回模糊查询的字符串
*/
public static String ToLikeStr(String str) {
if (str != null && str.length() > 0) {
str = str.trim().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_").replace("[", "\\[").replace("]", "\\]");
}
return str;
}
}
mybatis mapper配置文件:
<if test="targetStr!= null and targetStr!= ''">
<--and tb_demo.tb_target like "%"#{targetStr,jdbcType=VARCHAR}"%"-->
and tb_demo.tb_target like concat("%", #{contractNo,jdbcType=VARCHAR},"%")
</if>
在进行模糊查询的时候便能够对把mysql中把这些特殊字符不当作 皮配符处理,便不会查出所有数据
sql执行sql,后台打印的sql;
select * from tb_demo WHERE tb_demo.name ='\%\_' and tb_demo.phone like "%"'\%\_'"%"