mybatis 打印慢查询日志
1. 配置日志框架
MyBatis 本身支持多种日志框架,如 Log4j、Log4j2、SLF4J 等。这里以 SLF4J 和 Logback 为例进行配置。
将 com.yourcompany.yourproject.dao 替换为你实际的 DAO 接口所在的包名。
2. 自定义拦截器
通过自定义拦截器来记录慢查询日志。以下是一个示例代码:
java
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Statement;
import java.util.Properties;
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class SlowQueryInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(SlowQueryInterceptor.class);
// 慢查询时间阈值,单位:毫秒
private long slowQueryThreshold = 1000;
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
if (executionTime > slowQueryThreshold) {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
String sql = statementHandler.getBoundSql().getSql();
logger.warn("Slow query detected! SQL: {}, Execution time: {} ms", sql, executionTime);
}
}
}
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
String threshold = properties.getProperty("slowQueryThreshold");
if (threshold != null) {
slowQueryThreshold = Long.parseLong(threshold);
}
}
}
3. 配置拦截器
在 MyBatis 的配置文件(如 mybatis-config.xml)中配置拦截器:
xml
<plugins>
<plugin interceptor="com.yourcompany.yourproject.interceptor.SlowQueryInterceptor">
<property name="slowQueryThreshold" value="1000" />
</plugin>
</plugins>
将 com.yourcompany.yourproject.interceptor.SlowQueryInterceptor 替换为你实际的拦截器类的全限定名,slowQueryThreshold 为慢查询时间阈值,单位是毫秒。
总结
通过以上步骤,你可以在 MyBatis 中实现慢查询日志的打印。自定义拦截器会在 SQL 执行前后记录时间,当执行时间超过设定的阈值时,会将 SQL 语句和执行时间记录到日志中,方便你后续进行分析和优化。
mybatis 打印sql日志
# mybatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.ltkj.ticket
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
或者:下面结合