实现Mybatis官方提供的拦截器,用于记录SQL语句的执行时间
package com.github.bjlhx15.mybatis; /** * @author lihongxu * @since 2018/11/15 下午4:02 */ import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Statement; import java.util.Properties; /** * Sql执行时间记录拦截器 */ @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 SqlCostInterceptor implements Interceptor { Logger logger = LoggerFactory.getLogger(SqlCostInterceptor.class); @Override public Object intercept(Invocation invocation) throws Throwable { long startTime = System.currentTimeMillis(); StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); final BoundSql boundSql = statementHandler.getBoundSql(); try { return invocation.proceed(); } finally { final StringBuilder build = new StringBuilder(7); build.append("\n"); build.append("------------sql执行耗时计算开始---------------"); build.append("\n"); build.append("SQL:"); build.append(boundSql.getSql()); build.append("\n"); build.append("MYBATIS-SQL执行耗时:["); build.append((System.currentTimeMillis() - startTime)); build.append("ms]"); build.append("\n"); build.append("------------sql执行耗时计算结束---------------"); logger.warn(build.toString()); } } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
注:Interceptor接口是Mybatis官方提供的拦截接口,创建一个类实现该接口并重写其三个方法并将该类配置在Mybatis的配置文件中,即可拦截SQL语句的执行过程
手动编写执行的配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="false" /> <setting name="lazyLoadingEnabled" value="false" /> <setting name="multipleResultSetsEnabled" value="true" /> <setting name="useColumnLabel" value="true" /> <setting name="useGeneratedKeys" value="false" /> <setting name="defaultExecutorType" value="SIMPLE" /> <setting name="defaultStatementTimeout" value="30" /> <!--<setting name="logImpl" value="LOG4J2" />--> </settings> <plugins> <!-- 拦截器配置 --> <plugin interceptor="com.github.bjlhx15.mybatis.SqlCostInterceptor" /> </plugins> </configuration>