一. 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;
}
}