SoFunction
Updated on 2025-05-08

How to use mybatis interceptor (output log or sql statement)

A function of an interceptor

We can intercept calls to certain methods. We can choose to add some logic before and after the execution of these intercepted methods. We can also execute our own logic when executing these intercepted methods without executing the intercepted methods.

One of the original intentions of Mybatis interceptor design is to enable users to implement their own logic at some point without having to touch Mybatis' inherent logic. Mybatis interceptor is generally used for paging plugins, output logs, sql, etc.

How to use

First, I need to implement mybatis' Interceptor interface.

Three ways to implement it:

Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);

The plugin method is used by the interceptor to encapsulate the target object. Through this method, we can return the target object itself or return its proxy.

When the returned proxy is the proxy, we can intercept the methods to call the intercept method, and of course we can also call other methods, which will be explained later.

  • setPropertiesThe method is used to specify some properties in the Mybatis configuration file.
  • pluginIn the method, we can decide whether to intercept and then decide what kind of target object to return. The intercept method is the method to be executed when intercepting.

The following example is originally used to record logs to the database

However, since mybatis cannot inject spring objects under the underlying layer, it can only be used to output logs.

@Intercepts({@Signature(method = "update", type = , args = {, })})
public class LogInterceptor implements Interceptor {
    /**
      * Annotation method of intercepting interface
      * Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClose)
      * ParameterHandler (getParameterObject, setParameters)
      * ResultSetHandler (handleResultSets, handleOutputParameters)
      * StatementHandler (prepare, parameterize, batch, update, query)
      */

    private static final Logger LOGGER = ();

    private Properties properties;

    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = ();
        // Get the execution method        if ( > 1) {
            // The object passed in            Object obj = args[1];
            if (obj instanceof Log) {
                // If it is a log object, skip it directly                return ();
            }
            saveLog(args[0], obj);
        }
        return ();
    }

    private void saveLog(Object arg, Object obj) {
        Log log = new Log();
        (());
        (());
        MappedStatement mappedStatement = (MappedStatement) arg;
        // Execute method name        String name = ().name();
        String change = (obj);
        if (("INSERT")) {
            ("New" + ().getSimpleName());
            (change);
        } else if (("UPDATE")) {
            ("Revise" + ().getSimpleName());
            (change);
        } else if (("DELETE")) {
            ("delete" + ().getSimpleName());
            (change);
        }

        ("----------------------------------------------");
        ((log));
        ("----------------------------------------------");
    }

    public Object plugin(Object target) {
        return (target, this);
    }

    public void setProperties(Properties properties) {
         = properties;
    }

}

The @Intercepts annotation must be added on the class

@Signature, represents the intercept point,

@Intercepts({@Signature(method = "update", type = , args = {, })})

method means the method that needs to be intercepted

mybatis has methods such as update, query, flushStatements, commit, rollback, getTransaction, close, isClosed, etc. Among them, update includes methods such as adding, modifying, and deleting. Query is used for querying, but other methods are basically not available.

  • typeIt represents the interface type to intercept, including Executor, StatementHandler, ParameterHandler and ResultSetHandler.
  • argsThe parameter types representing the intercepted include MappedStatement, Object, RowBounds, ResultHandler, etc.

Write the interceptor

Need to register an interceptor in the configuration file and add it to the sqlMapConfig configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-////DTD Config 3.0//EN"
        "/dtd/">
<configuration>
  <settings>
      <setting name="cacheEnabled" value="true"/>
      <setting name="lazyLoadingEnabled" value="true"/>
      <setting name="multipleResultSetsEnabled" value="true"/>
      <setting name="useColumnLabel" value="true"/>
      <setting name="useGeneratedKeys" value="false"/>
    </settings>
    
    <plugins>
        <plugin interceptor=""></plugin>
    </plugins>
</configuration>

Start the project test

The output log is as follows:

2016-08-28 14:48:02 [ http-apr-8888-exec-8:70630 ] - [ INFO ] ----------------------------------------------
2016-08-28 14:48:02 [ http-apr-8888-exec-8:70634 ] - [ INFO ] {"recordId":null,"type":"Modify User","oldContent":null,"newContent":"{\"recordId\":1,\"username\":\"wdd\",\"telephone\":\"188888888888888\",\"sex\":2,\"password\":null,\"age\":22,\"status\":1,\"address\":\"Anhui Lingbi 1\",\"pho to\":null,\"email\":\"asdds\",\"qq\":\"812908087\",\"nickname\":\"Fish that loves to eat cats1\",\"registerTime\":null,\"modifyTime\":1472366881824}","userId":null,"username":null,"createTime":1472366881824,"modifyTime":1472366881824}
2016-08-28 14:48:02 [ http-apr-8888-exec-8:70634 ] - [ INFO ] ----------------------------------------------

To insert into the database, you must new a dao object operation

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.