One article to understand mybatis plug-in development

MyBatis allows you to intercept calls at a certain point during the execution of the mapped statement. By default, MyBatis allows the use of plug-ins to intercept method calls including:

  • Executor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler(getParameterObject, setParameters)
  • ResultSetHandler: (handleResultSets, handleOutputParameters)
  • StatementHandler: (prepare, parameterize, batch, update, query)

Through the powerful mechanism provided by MyBatis, it is very simple to use the plug-in. You only need to implement the Interceptor interface and specify the signature of the method you want to intercept.

// ExamplePlugin.java
@Intercepts({
    
    @Signature(
  type= Executor.class,
  method = "update",
  args = {
    
    MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
    
    
  private Properties properties = new Properties();
  public Object intercept(Invocation invocation) throws Throwable {
    
    
    // implement pre processing if need
    Object returnObject = invocation.proceed();
    // implement post processing if need
    return returnObject;
  }
  public void setProperties(Properties properties) {
    
    
    this.properties = properties;
  }
}

The following configuration can be configured directly using Bean in springboot.

<!-- mybatis-config.xml -->
<plugins>
  <plugin interceptor="org.mybatis.example.ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>

The above plug-in will intercept all "update" method calls in the Executor instance, where Executor is the internal object responsible for executing the underlying mapping statement.

Analysis:
Let’s look at @Interceptsthis annotation first . There is only one parameter, which is an array.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
    
    
  Signature[] value();
}
@Intercepts({
    
    @Signature(
  type= Executor.class,
  method = "update",
  args = {
    
    MappedStatement.class,Object.class})})

Each element in the array is such an object. value of the type described above may be four phases, Executor.class, ParameterHandler.class, ResultSetHandler.class, StatementHandler.class
methodi.e., the method defined above, the method described above is four stages class, args, compared with the parameters of these methods. There is not much explanation about the specific meaning of the four stages, see the name knows the meaning.
So what can we do with plugins?

  • 1. For example, you can do audit logs for database operations. xxx, when is a certain piece of data inserted, or a certain piece of data is modified, what is the original data?
  • 2. For example, paging.
  • 3. For example, some default fields are automatically set.

Guess you like

Origin blog.csdn.net/a807719447/article/details/111603929