How to Build a Custom MyBatis Plugin: Step-by-Step Guide

This article explains the MyBatis plugin mechanism, walks through implementing the Interceptor interface, configuring the plugin in mybatis-config.xml, provides a complete code example, and outlines common use cases such as SQL logging, performance monitoring, permission control, and automatic field filling.

java1234
java1234
java1234
How to Build a Custom MyBatis Plugin: Step-by-Step Guide

MyBatis Plugin Basics

MyBatis plugins allow developers to extend framework functionality by intercepting various stages of SQL execution (before execution, after execution, result mapping, etc.). A plugin is created by implementing the org.apache.ibatis.plugin.Interceptor interface, whose core method is intercept(Invocation invocation).

1. Implement the Interceptor Interface

Write a class that implements org.apache.ibatis.plugin.Interceptor and overrides three methods: intercept(Invocation invocation): core logic to run before or after the target method. plugin(Object target): wraps the target object, typically checking if it is an Executor before applying the interceptor. setProperties(Properties properties): receives custom configuration parameters.

2. Configure the Plugin

Add the plugin definition to mybatis-config.xml inside the <plugins> element.

<configuration>
    <plugins>
        <plugin interceptor="com.example.mybatis.plugin.MyBatisLoggingPlugin"/>
    </plugins>
</configuration>

3. Plugin Code Example

package com.example.mybatis.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.mapping.MappedStatement;
import java.sql.Statement;
import java.util.Properties;

public class MyBatisLoggingPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        if (target instanceof Executor) {
            Object[] args = invocation.getArgs();
            for (Object arg : args) {
                if (arg instanceof MappedStatement) {
                    MappedStatement ms = (MappedStatement) arg;
                    System.out.println("Executing SQL: " + ms.getSqlSource());
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        // Retrieve custom properties if needed
    }
}

4. Extension Points Explained

intercept(Invocation invocation)

: receives all information about the target method, including the target object and arguments. Call invocation.proceed() to execute the original method. plugin(Object target): decides whether to wrap the target based on its type. setProperties(Properties properties): allows reading custom configuration parameters.

5. Common Target Object Types

Executor : Executes SQL statements; typical for query and update interception.

StatementHandler : Generates SQL and handles pre‑execution processing.

ParameterHandler : Manages parameter setting.

ResultSetHandler : Processes query results.

6. Compile and Use the Plugin

After compiling the plugin, ensure the resulting JAR is on MyBatis’s classpath and that the plugin is correctly referenced in mybatis-config.xml.

Typical Plugin Use Cases

SQL Logging : Record execution time, SQL statement, and parameters for each query.

Performance Monitoring : Measure execution duration before and after SQL execution to aid optimization.

Permission Control : Check user permissions before running a statement and modify SQL dynamically.

Automatic Field Filling : Auto‑populate fields such as creation time or update time during insert operations.

JavaSQLpluginMyBatisInterceptor
java1234
Written by

java1234

Former senior programmer at a Fortune Global 500 company, dedicated to sharing Java expertise. Visit Feng's site: Java Knowledge Sharing, www.java1234.com

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.