import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.*; /** * mybatis/mybatis-plus模糊查询语句特殊字符转义拦截器 * * @author lieber */ @Intercepts ({
@Signature (type = Executor. class , method = "query" , args = {MappedStatement. class , Object. class , RowBounds. class , ResultHandler. class })}) @Slf4j public class MybatisLikeSqlInterceptor implements Interceptor {
/** * SQL语句like */ private final static String SQL_LIKE = " like " ; /** * SQL语句占位符 */ private final static String SQL_PLACEHOLDER = "?" ; /** * SQL语句占位符分隔 */ private final static String SQL_PLACEHOLDER_REGEX = "\\?" ; /** * 所有的转义器 */ private static Map<Class, AbstractLikeSqlConverter> converterMap = new HashMap<>( 4 ); static {
converterMap.put(Map. class , new MapLikeSqlConverter()); converterMap.put(Object. class , new ObjectLikeSqlConverter()); } @Override public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs(); MappedStatement statement = (MappedStatement) args[ 0 ]; Object parameterObject = args[ 1 ]; BoundSql boundSql = statement.getBoundSql(parameterObject); String sql = boundSql.getSql(); this .transferLikeSql(sql, parameterObject, boundSql); return invocation.proceed(); } @Override public Object plugin(Object target) {
return Plugin.wrap(target, this ); } @Override public void setProperties(Properties arg0) {
} /** * 修改包含like的SQL语句 * * @param sql SQL语句 * @param parameterObject 参数对象 * @param boundSql 绑定SQL对象 */ private void transferLikeSql(String sql, Object parameterObject, BoundSql boundSql) {
if (!isEscape(sql)) {
return ; } sql = sql.replaceAll( " {2}" , " " ); // 获取关键字的个数(去重) Set<String> fields = this .getKeyFields(sql, bou
|