mysql  mybatis 环境:

1>. 处理sql特殊字符 {"*","%","_"} --> 替换为 "/*","/%","/_"

2>.   sql 中处理,定义‘/’ 为转义字符  


public abstract class BaseEntity extends PrimaryKeyObject {

private static final long serialVersionUID = 1L;

@Transient // 用于注释pojo对象中的属性,被注释的属性将成为短暂的,不会持久化。

protected Boolean escapeChar;  // 是否包含转义字符

protected String keyword;   // 模糊查询关键字


public String getKeyword() {

return keyword == null ? null : keyword.trim();

}


public void setKeyword(String keyword) {

this.keyword = keyword == null ? null : keyword.trim();

}


public Boolean getEscapeChar() {

this.getNewKeyword();

return escapeChar;

}


public void setEscapeChar(Boolean escapeChar) {

this.escapeChar = escapeChar;

}


// 处理sql特殊字符 {"*","%","_"} --> 替换为 "/*","/%","/_"

private void getNewKeyword() {

if (escapeChar == null) {

escapeChar = false;

}

if (StringUtils.isNotEmpty(keyword) && !escapeChar) {

Pattern p1 = Pattern.compile("\\*|%|_");

Matcher m1 = p1.matcher(keyword);


StringBuffer buf = new StringBuffer();

while (m1.find()) {

m1.appendReplacement(buf, "/" + m1.group());

}

m1.appendTail(buf);

String newkeyword = buf.toString();


if (!keyword.equals(newkeyword)) {

this.setEscapeChar(true);

this.setKeyword(newkeyword);

}

}

}

}




and (

name like CONCAT("%",#{keyword},"%") escape '/'

or 

uname like CONCAT("%",#{keyword},"%") escape '/'

)