1. 自定义插件 CharEscapeInnerInterceptor ,继承InnerInterceptor
public class CharEscapeInnerInterceptor implements InnerInterceptor {
@SneakyThrows
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (parameter instanceof MapperMethod.ParamMap){
MapperMethod.ParamMap map= (MapperMethod.ParamMap)parameter;
map.keySet().forEach(key->{
if (map.get(key)!=null){
map.put(key,charEscape(map.get(key).toString()));
}
});
}else if (parameter instanceof String){
Field f=parameter.getClass().getDeclaredField("value");
f.setAccessible(true);
f.set(parameter,charEscape(parameter.toString()).toCharArray());
}
System.out.println(parameter);
}
private String charEscape(String charString) {
if (!StringUtils.hasLength(charString)) {
return charString;
}
charString = charString.trim();
if (charString.contains("\\")) {
charString = charString.replaceAll("\\\\", "\\\\");
}
if (charString.contains("%")) {
charString = charString.replaceAll("%", "\\\\%");
}
if (charString.contains("_")) {
charString = charString.replaceAll("_", "\\\\_");
}
return charString;
}
}
2. 修改mybatis配置 ,添加拦截器
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new CharEscapeInnerInterceptor());
return interceptor;
}
}
3. 测试
结果:传入参数为% ,查询时sql参数为/% ,参数已转义
|