MyBatis Interceptor: Data Source Detection

MyBatis Interceptor is a plugin used to intercept the process of SQL execution, allowing for operations such as printing the SQL statement and recording execution time before and after executing the SQL statement.

To determine the data source, you can access the current SqlSession object in the Interceptor’s interception method, then retrieve the data source information from the SqlSession object.

Here is a simple example code:

public class DataSourceInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取当前执行的SqlSession对象
        SqlSession sqlSession = (SqlSession) invocation.getArgs()[0];
        
        // 获取当前数据源信息
        DataSource dataSource = sqlSession.getConfiguration().getEnvironment().getDataSource();
        
        // 判断数据源类型
        if(dataSource instanceof PooledDataSource) {
            System.out.println("使用的数据源是PooledDataSource");
        } else if(dataSource instanceof UnpooledDataSource) {
            System.out.println("使用的数据源是UnpooledDataSource");
        } else {
            System.out.println("使用的数据源未知类型");
        }
        
        // 执行原始方法
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // Do nothing
    }
}

In the example above, we have implemented a DataSourceInterceptor that intercepts the method ‘intercept’ to retrieve the current SqlSession object. We use the SqlSession to obtain information about the data source in order to determine its type. Based on the type of data source, we can perform different actions.

bannerAds