SoFunction
Updated on 2025-04-11

Implementation of Proxy Pattern of Mybatis framework

MyBatis framework is widely usedProxy Pattern, especially inMapper interfaceon the implementation. The proxy mode allows MyBatis to dynamically provide interface implementation without directly implementing the interface, thereby simplifying database operation code while providing more powerful functions. The following will explain in detail the working principle and implementation of the proxy mode in MyBatis.

1. What is Proxy Pattern?

Agent ModeIt is a structural design pattern that provides an object with a proxy object to control access to this object. A proxy object usually pre-processes or post-processes the request and then passes the request to the actual target object.

Features of the proxy mode

  • Control access: Control access to the target object through proxy objects.
  • Delay loading: Lazy loading can be implemented in the proxy.
  • Enhanced features: Additional operations (such as logging, permission checking, transaction management, etc.) can be performed before or after the target object is called.

2. Application of proxy mode in MyBatis

In MyBatis, the main application scenarios of the proxy mode areMapper interface. Developers only need to define the Mapper interface, without providing an implementation class for the interface. MyBatis creates dynamic proxy objects for these interfaces at runtime, and executes SQL statements through proxy objects.

2.1 How to use proxy mode in MyBatis

  • Mapper interface: User-defined interface used to declare database operation methods (such asgetUserByIdinsertUserwait).
  • Mapper Dynamic Agent: MyBatis byJDK Dynamic ProxyGenerate proxy objects for the Mapper interface.
  • ()method: Used to obtain a proxy instance of the Mapper interface. When calling a method of a proxy instance, MyBatis will intercept and execute the corresponding SQL statement.

3. Workflow of agent mode

3.1 Working principle

  • The developer defines a Mapper interface and declares the database operation method.
  • pass(Class<T> clazz)Methods to obtain the proxy object of the interface.
  • When calling the proxy object method, MyBatis will passMapperProxyIntercept method calls.
  • MapperProxypassMappedStatementFind the corresponding SQL statement and perform the corresponding database operations.
  • Encapsulate the query result into the return type of the interface method (such asList<User>)。

3.2 Mapper agent diagram

UserMapper (interface)
    ↓
()
    ↓
MapperProxy (JDK Dynamic Agent)
    ↓
MappedStatement (Mapping SQL)
    ↓
implement SQL and return the result

4. Actual code examples

4.1 Create a Mapper Interface ()

package ;

import ;
import ;

public interface UserMapper {
    // Query all users    List&lt;User&gt; getAllUsers();

    // Query the user by ID    User getUserById(int id);
}

4.2 Writing Mapper XML Files ()

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-////DTD Mapper 3.0//EN"
    "/dtd/">
<mapper namespace="">
    <select  resultType="">
        SELECT * FROM users;
    </select>

    <select  parameterType="int" resultType="">
        SELECT * FROM users WHERE id = #{id};
    </select>
</mapper>

4.3 MyBatis configuration file ()

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-////DTD Config 3.0//EN"
    "/dtd/">
<configuration>
    <environments default="development">
        <environment >
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value=""/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mapper/"/>
    </mappers>
</configuration>

4.4 Use SqlSession to obtain Mapper proxy object ()

import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class MyBatisExample {
    public static void main(String[] args) {
        String resource = "";
        try (InputStream inputStream = (resource)) {
            // Create SqlSessionFactory            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // Open SqlSession            try (SqlSession session = ()) {
                // Get the proxy object of the Mapper interface                UserMapper userMapper = ();

                // Call the proxy object method                List&lt;User&gt; users = ();
                (user -&gt; (()));

                // Query the user by ID                User user = (1);
                ("User ID 1: " + ());
            }
        } catch (Exception e) {
            ();
        }
    }
}

5. Implementation details of MyBatis proxy mode

  • MapperProxykind: MyBatis useMapperProxyClasses to implement JDK dynamic proxy.MapperProxyImplementedInvocationHandlerInterface, used to intercept calls to Mapper interface methods.

  • MapperMethodkindMapperProxyThe intercepted method call will be delegated toMapperMethodObject.MapperMethodFind the corresponding one based on the method nameMappedStatement, and then execute the corresponding SQL statement.

MapperProxy Example (simplified version)

public class MapperProxy implements InvocationHandler {
    private SqlSession sqlSession;
    private Class<?> mapperInterface;

    public MapperProxy(SqlSession sqlSession, Class<?> mapperInterface) {
         = sqlSession;
         = mapperInterface;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String statementId = () + "." + ();
        return (statementId, args);
    }
}

6. Advantages of the proxy model

  • Decoupling: Developers only need to define interfaces, no need to write implementation classes, and reduce the degree of code coupling.
  • Simplify the code: Reduce duplicate database operation code and improve development efficiency.
  • Dynamic: Through the dynamic proxy mechanism, dynamically generate proxy objects at runtime to reduce hard coding.
  • Flexible expansion: Interceptors can be added easily to implement functions such as logging, permission verification, transaction control, etc.

7. Deficiencies in proxy mode

  • Performance overhead: Dynamic proxy has certain performance overhead when calling method, especially in high concurrency scenarios.
  • Debugging difficulty: Since there is no actual implementation class, it is impossible to jump directly to the method implementation during debugging, and the debugging complexity increases.
  • Learning Cost: For developers who are not familiar with the dynamic proxy mechanism, it may be difficult to understand the internal workings of MyBatis.

8. Summary

MyBatis greatly simplifies database operation code through proxy mode, allowing developers to focus more on business logic than SQL operations. The core of the MyBatis proxy mode is to use the JDK dynamic proxy mechanism to generate proxy objects for the Mapper interface at runtime, thereby mapping the interface method to the corresponding SQL statement execution. The use of proxy mode improves the flexibility and scalability of MyBatis and is one of its important design highlights.

This is the end of this article about the Proxy Pattern of the Mybatis framework. For more related content on Mybatis proxy mode, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!