结合MyBatis插件和Durid实现sql表动态修改

使用场景:系统要支持多租户,原设计针对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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值