简体   繁体   English

MyBatis 执行 SQL 时如何获取数据源?

[英]How to get datasource while MyBatis executing a SQL?

I am using MyBatis Interceptor to capture the SQL to be executed.我正在使用 MyBatis Interceptor 来捕获要执行的 SQL。 However, I am not able to get the datasource that is going to execute the SQL.但是,我无法获取将要执行 SQL 的数据源。
Is there a way in Java that I can get the specific dataSource? Java 中有没有办法获取特定的数据源?

Found a solution after some time.一段时间后找到了解决方案。 By implementing MyBatis's Interceptor interface, we could get the mappedStatement every time we execute a SQL.通过实现MyBatis 的Interceptor 接口,我们可以在每次执行SQL 时获取mappedStatement。 From mappedStatement, the dataSource could be obtained.从mappedStatement,可以得到dataSource。

private static final Logger logger = LoggerFactory.getLogger(DatasourceInterceptor.class);

@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object target = invocation.getTarget();
    Object result;
    Optional<DataSource> dataSourceOpt = Optional.empty();
    if (target instanceof Executor) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        if (mappedStatement.getConfiguration() != null
                && mappedStatement.getConfiguration().getEnvironment() != null) {
            dataSourceOpt = Optional.of(mappedStatement.getConfiguration().getEnvironment().getDataSource());
        }  
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        String sql = boundSql.getSql();
        logger.debug("executor SQL:{}", sql);
    }  
    result = invocation.proceed();
    return result; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM