在 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 配置文件(mybatis-config.xml)中: <!-- ... --> <plugins> <plugin interceptor="com.example.LoggingInterceptor"/> </plugins> <!-- ... --></configuration>现在,每次执行 SQL 查询时,拦截器都会记录 SQL 语句和执行时间。你可以根据需要修改 LoggingInterceptor 类以实现更复杂的日志记录功能。