Article From:

Implement Mybatis’s official interceptor for recording the execution time of SQL statements

package com.github.bjlhx15.mybatis;

 * @author lihongxu
 * @since 2018/11/15 4:02 p.m.*/

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;

 * SqlExecution Time Record Interceptor*/
@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);

    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("------------sqlStart executing time-consuming calculations);
            build.append("MYBATIS-SQLExecution time: [);
            build.append((System.currentTimeMillis() - startTime));
            build.append("------------sqlExecution Time-consuming Computing End - -----------");

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);

    public void setProperties(Properties properties) {


Note: The Interceptor interface is the official interception interface provided by Mybatis. To intercept the execution of SQL statements, create a class to implement the interface, rewrite its three methods and configure the class in the configuration file of Mybatis.

Write the executed configuration file manually

<?xml version="1.0"  encoding="UTF-8"  ?>
<!DOCTYPE configuration PUBLIC  "-// Config 3.0//EN" 


        <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" />-->
        <!-- Interceptor configuration - & gt;Plugin interceptor = "com.github.bjlhx15.mybatis.SqlCostInterceptor"/>< /plugins>Lt; / configuration & gt;


Leave a Reply

Your email address will not be published. Required fields are marked *