在 MyBatis 中,你可以使用攔截器(Interceptor)來實現日志記錄。攔截器允許你在 MyBatis 的核心方法之前和之后執行自定義代碼。要實現日志記錄,你需要創建一個自定義攔截器類并重寫相應的方法。
以下是一個簡單的示例,展示了如何創建一個攔截器來記錄 SQL 查詢和執行時間:
org.apache.ibatis.plugin.Interceptor
接口:import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
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})
})
public class LoggingInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = invocation.proceed();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
String sql = statementHandler.getBoundSql().getSql();
System.out.println("SQL: " + sql);
System.out.println("Execution time: " + duration + " ms");
return result;
}
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
// You can read custom properties from the configuration file here
}
}
mybatis-config.xml
)中: <!-- ... -->
<plugins>
<plugin interceptor="com.example.LoggingInterceptor"/>
</plugins>
<!-- ... -->
</configuration>
現在,每次執行 SQL 查詢時,攔截器都會記錄 SQL 語句和執行時間。你可以根據需要修改 LoggingInterceptor
類以實現更復雜的日志記錄功能。