【MySQL】Mybatis-Plus解决多数据源无法输出SQL语句的问题

一. Mybatis-Plus配置输出SQL语句

1. 原理

使用PerformanceInterceptor拦截器的intercept()方法输出SQL语句

2. 步骤

2.1 配置文件新增

mybatis-plus:
	configuration:
		log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2.2 新增PerformanceInterceptor对象

public class MybatisPlusConfig {
  	@Bean
    public PerformanceInterceptor performanceInterceptor() {

	        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
	        performanceInterceptor.setWriteInLog(true);
	        return performanceInterceptor;
    	}
    }

2.3 控制台输出

Time:执行耗时
Execute SQL:SELECT * FROM table WHERE ID=1 (SQL语句)

二. 多数据源无法输出SQL语句解决方法

SqlSessionFactory对象初始化时新增代码

public SqlSessionFactory sqlSessionFactory()
{

	MybatisConfiguration configuration = new MybatisConfiguration();

	// 新增代码
    configuration.addInterceptor(new PerformanceInterceptor());

    sqlSessionFactory.setConfiguration(configuration);

}

三. 输出SQL部分源码

public class PerformanceInterceptor implements Interceptor {

    public Object intercept(Invocation invocation) throws Throwable {

    	// 其它代码

		// 计算执行 SQL 耗时
        long start = SystemClock.now();
        Object result = invocation.proceed();
        long timing = SystemClock.now() - start;

        // 格式化 SQL 打印执行结果
        Object target = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(target);
        MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        StringBuilder formatSql = new StringBuilder();
        
        // 执行耗时
        formatSql.append(" Time:").append(timing);   
        
        // Mapper接口方法完整路径
        formatSql.append(" ms - ID:").append(ms.getId());
        
        // SQL语句
        formatSql.append("\n Execute SQL:").append(SqlUtils.sqlFormat(originalSql, format)).append("\n");
        
        if (this.isWriteInLog()) {
            if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {
                logger.error(formatSql.toString());
            } else {
                logger.debug(formatSql.toString());
            }
        } else {
            System.err.println(formatSql.toString());
            if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {
                throw new MybatisPlusException(" The SQL execution time is too large, please optimize ! ");
            }
        }
        return result;
    }
}
posted @ 2021-03-02 12:18    阅读(1510)  评论(0编辑  收藏  举报