使用场景:系统要支持多租户,原设计针对bhd租户除了分库路由,还会在表名前拼接"bhd_",在mapper.xml文件中的相关sql语句为原始表名.
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter;
public class ReWriteTableNameVisitor extends MySqlASTVisitorAdapter {
private static final String prefix="bhd_";
@Override
public boolean visit(SQLExprTableSource x) {
x.setExpr(prefix + x.getExpr());
x.getExpr().accept(this);
return false;
}
}
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class TenantTableNameInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
if(ToolUtil.isYHTenant()){
return invocation.proceed();
}
Object[] args = invocation.getArgs();
//获取MappedStatement对象
MappedStatement ms = (MappedStatement) args[0];
//获取传入sql语句的参数对象
Object parameterObject = args[1];
BoundSql boundSql = ms.getBoundSql(parameterObject);
//获取到拥有占位符的sql语句
String sql = boundSql.getSql();
System.out.println("拦截前sql :" + sql);
MySqlStatementParser mySqlStatementParser = new MySqlStatementParser(sql);
SQLStatement statement =mySqlStatementParser.parseStatement();
ReWriteTableNameVisitor visitor = new ReWriteTableNameVisitor();
statement.accept(visitor);
//重新生成一个BoundSql对象
BoundSql bs = new BoundSql(ms.getConfiguration(),statement.toString(),boundSql.getParameterMappings(),parameterObject);
System.out.println("拦截后sql :" + statement);
MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(bs));
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
bs.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
args[0] = newMs;
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
}
/***
* 复制一个新的MappedStatement
* @param ms
* @param newSqlSource
* @return
*/
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(ms.getKeyProperties()[0]);
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
/***
* MappedStatement构造器接受的是SqlSource
* 实现SqlSource接口,将BoundSql封装进去
*/
public static class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;
@Configuration
@AutoConfigureAfter({MybatisPlusAutoConfiguration.class})
public class MyBatisSqlReCoverConfiguration{
@Autowired
private List<SqlSessionFactory> sqlSessionFactoryList;
@PostConstruct
public void addTenantTableNameInterceptor() {
TenantTableNameInterceptor interceptor = new TenantTableNameInterceptor();
Iterator var3=this.sqlSessionFactoryList.iterator();
while(var3.hasNext()){
SqlSessionFactory sqlSessionFactory =(SqlSessionFactory)var3.next();
sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
}
}
}
效果:
拦截前sql :select count(1)
from supplier_update_apply_order s
left join (
select distinct apply_order_no
from wf_lbpm_audit_log_info
where model_id = ?
and is_delete = 0 and relation_type in
(
?
)
and handler_by_id = ?
) l on s.apply_order_no = l.apply_order_no
WHERE l.l.apply_order_no is not null and s.is_delete = 0
拦截后sql :SELECT COUNT(1)
FROM bhd_supplier_update_apply_order s
LEFT JOIN (
SELECT DISTINCT apply_order_no
FROM bhd_wf_lbpm_audit_log_info
WHERE model_id = ?
AND is_delete = 0
AND relation_type IN (?)
AND handler_by_id = ?
) l
ON s.apply_order_no = l.apply_order_no
WHERE l.l.apply_order_no IS NOT NULL
AND s.is_delete = 0