解決思路:自定義一個(gè)攔截器歹鱼,當(dāng)有模糊查詢時(shí),模糊查詢的關(guān)鍵字中包含有上述特殊字符時(shí)眨猎,在該特殊字符前添加
\
進(jìn)行轉(zhuǎn)義處理抑进。
一、問題提出
????使用MyBatis中的模糊查詢時(shí)睡陪,當(dāng)查詢關(guān)鍵字中包括有_
寺渗、\
、%
時(shí)兰迫,查詢關(guān)鍵字失效信殊。
二、問題分析
1汁果、當(dāng)like中包含_
時(shí)涡拘,查詢?nèi)詾槿浚?like '%_%'
查詢出來的結(jié)果與like '%%'
一致据德,并不能查詢出實(shí)際字段中包含有_
特殊字符的結(jié)果條目
2鳄乏、like中包括%
時(shí),與1中相同
3棘利、like中包含\
時(shí)橱野,帶入查詢時(shí),%\%
無法查詢到包含字段中有\
的條目
特殊字符 | 未處理 | 處理后 |
---|---|---|
_ | like '%_%' |
like '%\_%' |
% | like '%%%' |
like '%\%%' |
\ | like '%\%' |
like '%\\%' |
ESCAPE '/'
必須加在SQL的最后善玫。like '%\_%'
效果與like concat('%', '\_', '%')
相同
三水援、問題解決
1、自定義攔截器方法類
處理[對(duì)象.屬性]的特殊字符處理時(shí)使用到了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模糊查詢時(shí)將指定字符進(jìn)行替換,防止注入
* 參見{@link EscapeUtil#escapeChar}
* <p>
* 說明:
* 1.支持在Mapper層使用[對(duì)象.屬性]的like查詢
* 2.解決了在QueryWrapper或LambdaQueryWrapper下的左右及全匹配模糊查詢下參數(shù)中特殊字符的精確替換問題
* 3.解決在QueryWrapper或LambdaQueryWrapper下存在多個(gè)查詢關(guān)鍵字時(shí)的左右及全匹配模糊查詢下參數(shù)中特殊字符的精確替換問題
*
* @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;
// 修改只洒,同時(shí)支持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();
// 獲取參數(shù)序號(hào) 當(dāng)存在多個(gè)模糊查詢參數(shù)時(shí),參數(shù)名為 MPGENVAL1/MPGENVAL2/MPGENVAL3...
// 每個(gè)參數(shù)名與NormalSegmentList中參數(shù)值的對(duì)應(yīng)關(guān)系為(n-1)*4+2毕谴,n即為MPGENVAL后綴序號(hào) -- 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);
// 參數(shù)值對(duì)象 byte[]類型成畦,當(dāng)做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) {
/**
* 解決[對(duì)象.屬性]時(shí)的模糊查詢無法對(duì)特殊字符進(jìn)行轉(zhuǎn)義的問題
* 如模糊查詢參數(shù):req.name = %admin
* 需轉(zhuǎn)義為:req.name = \%admin
*/
// 使用.進(jìn)行分割后,第一個(gè)參數(shù)為類對(duì)象名涝开,第二個(gè)參數(shù)為類屬性字段名循帐,如req.name
String[] paramArr = keyName.split("\\.");
// 類對(duì)象
Object className = parameter.get(paramArr[0]);
// 類名
String name = className.getClass().getName();
// 將對(duì)象轉(zhuǎn)為JSON對(duì)象
JSONObject jsonObject = JSONObject.from(className);
// 參數(shù),進(jìn)行特殊字符串移除
String param = jsonObject.getString(paramArr[1]);
jsonObject.put(paramArr[1], EscapeUtil.escapeChar(param));
logger.info("[對(duì)象.屬性]模糊查詢進(jìn)行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
下的左右及全匹配模糊查詢下參數(shù)中特殊字符的精確替換問題 - 支持對(duì)[對(duì)象.屬性]的模糊查詢替換
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配置數(shù)據(jù)源拄养、sqlSessionFactory、事務(wù)管理器银舱、分頁插件瘪匿、自定義攔截器等
*/
@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;
}
// 自定義攔截器實(shí)現(xiàn)模糊查詢中的特殊字符處理
@Bean
public MyInterceptor myInterceptor() {
MyInterceptor sql = new MyInterceptor();
return sql;
}
// 數(shù)據(jù)源配置
@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);
// 設(shè)置MyBatis的插件/攔截器列表
List<Interceptor> interceptors = new ArrayList<>();
interceptors.add(paginationInterceptor);
interceptors.add(myInterceptor);
sessionFactory.setPlugins(interceptors.toArray(new Interceptor[1]));
return sessionFactory.getObject();
}
// 設(shè)置事務(wù)管理器跛梗,在需要事務(wù)的service層使用如下注解進(jìn)行事務(wù)管理
// @Transactional(transactionManager = "masterTransactionManager", rollbackFor = Exception.class)
@Bean(name = "masterTransactionManager")
public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
- 由于框架中使用多個(gè)數(shù)據(jù)源配置,因此使用數(shù)據(jù)庫事務(wù)時(shí)棋弥,優(yōu)先使用該事務(wù)時(shí)核偿,需要在該方法上顯著的添加
@Primary
注解
3、工具類:特殊字符轉(zhuǎn)義
import org.apache.commons.lang3.StringUtils;
public class EscapeUtil {
//mysql的模糊查詢時(shí)特殊字符轉(zhuǎn)義
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)語法即可
)
四漾岳、重點(diǎn)關(guān)注
以上方法在關(guān)鍵字中包含有\
可能會(huì)失效,失效的原因是由于查詢的關(guān)鍵字的數(shù)據(jù)庫字段排序規(guī)則為utf8_unicode_ci
粉寞,如下圖
要想不失效尼荆,查詢的關(guān)鍵字的排序規(guī)則必須為
utf8_general_ci
,如下圖或者統(tǒng)一全部數(shù)據(jù)庫字符集與排序規(guī)則分別為:
utf8mb4
與utf8mb4_general_ci
仁锯,如下圖【END】
文章參考
特殊字符查詢
動(dòng)態(tài)修改SQL語句
排序規(guī)則參考
- Mysql的utf8與utf8mb4區(qū)別翔悠,utf8mb4_bin业崖、utf8mb4_general_ci、utf8mb4_unicode_ci區(qū)別
- Mysql中的排序規(guī)則utf8_unicode_ci蓄愁、utf8_general_ci總結(jié)