解决思路:自定义一个拦截器,当有模糊查询时,模糊查询的关键字中包含有上述特殊字符时,在该特殊字符前添加
\
进行转义处理。
一、问题提出
使用MyBatis中的模糊查询时,当查询关键字中包括有_
、\
、%
时,查询关键字失效。
二、问题分析
1、当like中包含_
时,查询仍为全部,即 like '%_%'
查询出来的结果与like '%%'
一致,并不能查询出实际字段中包含有_
特殊字符的结果条目
2、like中包括%
时,与1中相同
3、like中包含\
时,带入查询时,%\%
无法查询到包含字段中有\
的条目
特殊字符 | 未处理 | 处理后 |
---|---|---|
_ | like '%_%' |
like '%\_%' |
% | like '%%%' |
like '%\%%' |
\ | like '%\%' |
like '%\\%' |
ESCAPE '/'
必须加在SQL的最后。like '%\_%'
效果与like concat('%', '\_', '%')
相同
三、问题解决
1、自定义拦截器方法类
处理[对象.属性]的特殊字符处理时使用到了fastjson2,注意依赖引入。
package cn.keyidea.common.config;
import cn.keyidea.common.util.EscapeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.segments.NormalSegmentList;
import com.baomidou.mybatisplus.core.enums.SqlLike;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.*;
/**
* Mybatis模糊查询时将指定字符进行替换,防止注入
* 参见{@link EscapeUtil#escapeChar}
* <p>
* 说明:
* 1.支持在Mapper层使用[对象.属性]的like查询
* 2.解决了在QueryWrapper或LambdaQueryWrapper下的左右及全匹配模糊查询下参数中特殊字符的精确替换问题
* 3.解决在QueryWrapper或LambdaQueryWrapper下存在多个查询关键字时的左右及全匹配模糊查询下参数中特殊字符的精确替换问题
*
* @author admin
* @date 2023-09-21
*/
@Intercepts(@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class
}))
public class MyQueryInterceptor implements Interceptor {
private final static Logger logger = LoggerFactory.getLogger(MyQueryInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 拦截sql
Object[] args = invocation.getArgs();
MappedStatement statement = (MappedStatement) args[0];
Object parameterObject = args[1];
BoundSql boundSql = statement.getBoundSql(parameterObject);
String sql = boundSql.getSql();
modifyLikeSql(sql, parameterObject, boundSql);
// 返回
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
@SuppressWarnings("unchecked")
public static String modifyLikeSql(String sql, Object parameterObject, BoundSql boundSql) throws NoSuchFieldException, ClassNotFoundException {
if (parameterObject instanceof HashMap) {
} else {
return sql;
}
if (!sql.toLowerCase().contains(" like ") || !sql.toLowerCase().contains("?")) {
return sql;
}
String[] strList = sql.split("\\?");
Set<String> keyNames = new HashSet<>();
for (int i = 0; i < strList.length; i++) {
if (strList[i].toLowerCase().contains(" like ")) {
String keyName = boundSql.getParameterMappings().get(i).getProperty();
keyNames.add(keyName);
}
}
for (String keyName : keyNames) {
HashMap parameter = (HashMap) parameterObject;
if (keyName.contains("ew.paramNameValuePairs.") && sql.toLowerCase().contains(" like ?")) {
Object ew = parameter.get("ew");
String[] keyList = keyName.split("\\.");
MergeSegments expression = null;
// 修改,同时支持QueryWrapper与LambdaQueryWrapper语法 -- modify by qyd 2023-04-23
if (ew instanceof QueryWrapper) {
QueryWrapper wrapper = (QueryWrapper) ew;
parameter = (HashMap) wrapper.getParamNameValuePairs();
expression = ((QueryWrapper<?>) ew).getExpression();
} else if (ew instanceof LambdaQueryWrapper) {
LambdaQueryWrapper wrapper = (LambdaQueryWrapper) ew;
parameter = (HashMap) wrapper.getParamNameValuePairs();
expression = ((LambdaQueryWrapper<?>) ew).getExpression();
}
if (expression == null) {
continue;
}
// 修改,支持精确的左右及全匹配模糊查询 -- modify by qyd 2024-07-05
NormalSegmentList normal = expression.getNormal();
// 获取参数序号 当存在多个模糊查询参数时,参数名为 MPGENVAL1/MPGENVAL2/MPGENVAL3...
// 每个参数名与NormalSegmentList中参数值的对应关系为(n-1)*4+2,n即为MPGENVAL后缀序号 -- modify by qyd 2024-07-29
int index = Integer.parseInt(keyList[2].substring(keyList[2].length() - 1));
ISqlSegment segment = normal.get((index - 1) * 4 + 2);
// 参数值对象 byte[]类型,当做String来处理
Object arg2 = null;
// LIKE匹配类型 SqlLike类型
Object arg3 = null;
try {
Field field3 = segment.getClass().getDeclaredField("arg$3");
field3.setAccessible(true);
arg3 = field3.get(segment);
Field field2 = segment.getClass().getDeclaredField("arg$2");
field2.setAccessible(true);
arg2 = field2.get(segment);
logger.info("arg2:{},arg3:{}", arg2, arg3);
} catch (NoSuchFieldException | IllegalAccessException e) {
logger.error("Failed to get arg$2 or arg$3", e);
continue;
}
if (arg3 instanceof SqlLike arg3Str && arg2 instanceof String arg2Value) {
String arg3Name = arg3Str.name();
switch (arg3Name) {
// 左匹配 -> LEFT
case "LEFT":
parameter.put(keyList[2], "%" + EscapeUtil.escapeChar(arg2Value));
break;
// 右匹配 -> RIGHT
case "RIGHT":
parameter.put(keyList[2], EscapeUtil.escapeChar(arg2Value) + "%");
break;
// 全匹配 -> DEFAULT
default:
parameter.put(keyList[2], "%" + EscapeUtil.escapeChar(arg2Value) + "%");
break;
}
}
} else if (!keyName.contains("ew.paramNameValuePairs.") && sql.toLowerCase().contains(" like ?")) {
Object a = parameter.get(keyName);
if (a instanceof String && (a.toString().contains("_") || a.toString().contains("\\") || a.toString()
.contains("%"))) {
parameter.put(keyName,
"%" + EscapeUtil.escapeChar(a.toString().substring(1, a.toString().length() - 1)) + "%");
}
} else if (keyName.contains(".") && keyName.split("\\.").length == 2) {
/**
* 解决[对象.属性]时的模糊查询无法对特殊字符进行转义的问题
* 如模糊查询参数:req.name = %admin
* 需转义为:req.name = \%admin
*/
// 使用.进行分割后,第一个参数为类对象名,第二个参数为类属性字段名,如req.name
String[] paramArr = keyName.split("\\.");
// 类对象
Object className = parameter.get(paramArr[0]);
// 类名
String name = className.getClass().getName();
// 将对象转为JSON对象
JSONObject jsonObject = JSONObject.from(className);
// 参数,进行特殊字符串移除
String param = jsonObject.getString(paramArr[1]);
jsonObject.put(paramArr[1], EscapeUtil.escapeChar(param));
logger.info("[对象.属性]模糊查询进行SQL特殊字符串处理,移除前:{},移除后:{}", param, jsonObject.get(paramArr[1]));
parameter.put(paramArr[0], jsonObject);
} else {
Object a = parameter.get(keyName);
if (a instanceof String && (a.toString().contains("_") || a.toString().contains("\\") || a.toString()
.contains("%"))) {
String s = EscapeUtil.escapeChar(a.toString());
parameter.put(keyName, s);
}
}
}
return sql;
}
}
说明
- 解决了在
QueryWrapper
或LambdaQueryWrapper
下的左右及全匹配模糊查询下参数中特殊字符的精确替换问题 - 支持对[对象.属性]的模糊查询替换
2、在配置类中添加自定义拦截器
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
/**
* MyBatis配置数据源、sqlSessionFactory、事务管理器、分页插件、自定义拦截器等
*/
@Configuration
@MapperScan(basePackages = {"com.keyidea.boss.mapper"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MybatisPlusConfig {
@Autowired
private MybatisPlusProperties properties;
// 使用MyBatis中的分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
return page;
}
// 自定义拦截器实现模糊查询中的特殊字符处理
@Bean
public MyInterceptor myInterceptor() {
MyInterceptor sql = new MyInterceptor();
return sql;
}
// 数据源配置
@Bean(name = "masterDataSource")
@ConfigurationProperties("spring.datasource")
@Primary
public DataSource masterDataSource() {
return DruidDataSourceBuilder.create().build();
}
// 配置sqlSessionFactory
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource,
PaginationInterceptor paginationInterceptor, MyInterceptor myInterceptor) throws Exception {
final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
if (this.properties.getConfigurationProperties() != null) {
sessionFactory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
GlobalConfig globalConfig = this.properties.getGlobalConfig();
sessionFactory.setGlobalConfig(globalConfig);
// 设置MyBatis的插件/拦截器列表
List<Interceptor> interceptors = new ArrayList<>();
interceptors.add(paginationInterceptor);
interceptors.add(myInterceptor);
sessionFactory.setPlugins(interceptors.toArray(new Interceptor[1]));
return sessionFactory.getObject();
}
// 设置事务管理器,在需要事务的service层使用如下注解进行事务管理
// @Transactional(transactionManager = "masterTransactionManager", rollbackFor = Exception.class)
@Bean(name = "masterTransactionManager")
public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
- 由于框架中使用多个数据源配置,因此使用数据库事务时,优先使用该事务时,需要在该方法上显著的添加
@Primary
注解
3、工具类:特殊字符转义
import org.apache.commons.lang3.StringUtils;
public class EscapeUtil {
//mysql的模糊查询时特殊字符转义
public static String escapeChar(String before){
if(StringUtils.isNotBlank(before)){
before = before.replaceAll("\\\\", "\\\\\\\\");
before = before.replaceAll("_", "\\\\_");
before = before.replaceAll("%", "\\\\%");
}
return before ;
}
}
4、版本信息参考
- JDK8+
- Mybatis Plus 3.1.0+
- fastjson2(
支持JSONObject.from(object)语法即可
)
四、重点关注
以上方法在关键字中包含有\
可能会失效,失效的原因是由于查询的关键字的数据库字段排序规则为utf8_unicode_ci
,如下图
要想不失效,查询的关键字的排序规则必须为
utf8_general_ci
,如下图或者统一全部数据库字符集与排序规则分别为:
utf8mb4
与utf8mb4_general_ci
,如下图【END】
文章参考
特殊字符查询
动态修改SQL语句
排序规则参考
- Mysql的utf8与utf8mb4区别,utf8mb4_bin、utf8mb4_general_ci、utf8mb4_unicode_ci区别
- Mysql中的排序规则utf8_unicode_ci、utf8_general_ci总结