package com.xxx.config;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.sql.Connection;
import java.util.Map;
import java.util.Properties;
/**
* @author nitmali
* @since 2022/5/30 9:45
*
* 去除参数两端空格
* 若有模糊匹配,去除 % 到字符间的空格
*/
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class RemoveSpacesInterceptor extends AbstractSqlParserHandler implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 递归h.target
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
// 先判断是不是SELECT操作
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
if (SqlCommandType.SELECT != mappedStatement.getSqlCommandType()
|| StatementType.CALLABLE == mappedStatement.getStatementType()) {
return invocation.proceed();
}
// mapper方法的全路径名
// TODO 根据注解判断是否需要忽略空格
String id = mappedStatement.getId();
BoundSql boundSql = statementHandler.getBoundSql();
if (!(boundSql.getParameterObject() instanceof MapperMethod.ParamMap)) {
return invocation.proceed();
}
MapperMethod.ParamMap<?> parameter = (MapperMethod.ParamMap<?>)boundSql.getParameterObject();
if (parameter.containsKey("ew") && parameter.get("ew") instanceof AbstractWrapper) {
// 获取到原始参数
Map<String, Object> paramNameValuePairs = ((AbstractWrapper<?, ?, ?>) parameter.get("ew")).getParamNameValuePairs();
paramNameValuePairs.entrySet()
.forEach(stringObjectEntry -> {
if (stringObjectEntry.getValue() instanceof String) {
// 去除两端空格
String regular = "(%?)\\s*([\\s\\S]*\\S+(?<!%))\\s*(%?)";
String value = ((String) stringObjectEntry.getValue());
stringObjectEntry.setValue(value.replaceAll(regular, "$1$2$3"));
}
});
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Interceptor.super.plugin(target);
}
@Override
public void setProperties(Properties properties) {
Interceptor.super.setProperties(properties);
}
}