簡體   English   中英

MyBatis 執行 SQL 時如何獲取數據源?

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

我正在使用 MyBatis Interceptor 來捕獲要執行的 SQL。 但是,我無法獲取將要執行 SQL 的數據源。
Java 中有沒有辦法獲取特定的數據源?

一段時間后找到了解決方案。 通過實現MyBatis 的Interceptor 接口,我們可以在每次執行SQL 時獲取mappedStatement。 從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