introduction
MyBatis-Plus (MP for short) is an enhanced framework for MyBatis throughBaseMapper
Provides general CRUD operations, greatly improving development efficiency. In order to understand its encapsulation mechanism more thoroughly, this article will adopt the thinking of link tracing, start from the developer calling the interface, and gradually penetrate into the core implementation of MyBatis-Plus, and analyze how it completes the encapsulation of BaseMapper based on MyBatis.
1. Start from the call: BaseMapper usage scenario
Suppose we have a simple entity classUser
And the corresponding Mapper interface:
@TableName("t_user") public class User { @TableId private Long id; private String name; private Integer age; // getter and setter omitted} public interface UserMapper extends BaseMapper<User> { }
The developer just needs to call this:
UserMapper userMapper = (); User user = (1L);
On the surface,selectById
yesBaseMapper
The method provided, but how is it implemented behind it? Let's follow the call link step by step.
2. Link tracking: from interface call to proxy execution
1. Get the Mapper proxy object
When called()
When MyBatis'sSqlSession
Will entrust it toConfiguration
ofgetMapper
method:
// MyBatis: public <T> T getMapper(Class<T> type, SqlSession sqlSession) { return (type, sqlSession); }
HeremapperRegistry
It's from MyBatisMapperRegistry
Class, but replaced in MyBatis-Plus withMybatisMapperRegistry
. Link to the custom implementation of MyBatis-Plus:
// MyBatis-Plus: public <T> T getMapper(Class<T> type, SqlSession sqlSession) { MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) (type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } return (sqlSession); }
-
Key points: MyBatis-Plus rewritten
MapperRegistry
and all inheritances are scanned at startupBaseMapper
Register the interface toknownMappers
middle. -
Agent Generation:
newInstance
Method created aMapperProxy
Object, this is the implementation of JDK dynamic proxy.
2. Method call intercept
When called(1L)
When the proxy objectMapperProxy
ofinvoke
The method is triggered:
// MyBatis-Plus: public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ((())) { return (this, args); } MybatisMapperMethod mapperMethod = cachedMapperMethod(method); return (sqlSession, args); }
-
Link fork:
cachedMapperMethod
Will cache according to the method signature and return aMybatisMapperMethod
Object. -
Execution Logic:
execute
The method determines the specific execution path based on the method name and parameters.
forselectById
, link entry:
// MyBatis-Plus: public Object execute(SqlSession sqlSession, Object[] args) { if ( == ()) { if (().isAssignableFrom()) { return ((), args); } return ((), args[0]); } // Other types such as INSERT, UPDATE, etc.}
-
Key points:
()
Returns a globally unique SQL ID, e.g.。
-
Execute SQL: The final call to MyBatis
selectOne
Methods execute query.
3. SQL injection: The implementation source of the BaseMapper method
The question is:selectById
Where does SQL come from? The answer lies in the SQL injection mechanism of MyBatis-Plus.
1. SQL injection at startup
MyBatis-Plus is passed when the Spring container is initializedMapperScannerConfigurer
Scan the Mapper interface and callISqlInjector
Inject universal SQL:
// MyBatis-Plus: public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) { List<AbstractMethod> methodList = getMethodList(mapperClass); for (AbstractMethod method : methodList) { (builderAssistant, mapperClass); } }
-
Method List:
getMethodList
returnBaseMapper
All methods defined in (e.g.selectById
、insert
etc.) implementation classes, for exampleSelectById
。 -
Injection process:by
SelectById
As an example:
// MyBatis-Plus: public void injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { String sql = ("<script>SELECT %s FROM %s WHERE %s = #{id}</script>", sqlSelectColumns(), (), ()); SqlSource sqlSource = (configuration, sql, modelClass); addSelectMappedStatement(mapperClass, "selectById", sqlSource, modelClass, tableInfo); }
-
SQL Generation:according to
TableInfo
(Resolve entity class through reflection) Dynamic generationSELECT * FROM t_user WHERE id = #{id}
。 -
register: Will be generated
MappedStatement
Registered to MyBatisConfiguration
middle.
2. The role of TableInfo
TableInfo
is the core metadata class of MyBatis-Plus, throughTableInfoHelper
Resolve entity classes at startup:
-
@TableName("t_user")
→ Table namet_user
。 -
@TableId
→ Primary Key Fieldid
。 - Field Mapping → Automatic Inference
name
、age
etc.
This information provides the basic data for SQL injection.
4. Link summary: the entire process from call to execution
-
Developer calls:
(1L)
。 -
Agent interception:
→
。
-
SQL execution:
→ MyBatis performs preinjection
MappedStatement
。 -
Result Mapping: MyBatis maps query results to
User
Object returns.
Support behind it:
-
At startup:Scan Mapper → Inject Universal SQL → Register
MappedStatement
。 - Runtime: Dynamic proxy → Method routing → SQL execution.
5. Collaboration and enhancement with MyBatis
-
Multiplex MyBatis: Dynamic proxy,
SqlSession
Core mechanisms such as , result mapping are completely inherited from MyBatis. -
Enhancement Point:
SQL Automation:pass
ISqlInjector
Inject universal SQL.Metadata management:
TableInfo
Implement automatic mapping of entities and tables.Conditional structure:
Wrapper
Extended dynamic query capabilities.
6. Conclusion
MyBatis-Plus encapsulation of BaseMapper is a clever extension of the MyBatis dynamic proxy and SQL execution framework. It implements zero configuration usage of universal CRUD through SQL injection at startup and proxy interception at runtime. Link tracking shows that this design not only retains the flexibility of MyBatis, but also greatly improves development efficiency through automation, which can be regarded as a "perfect completion" of MyBatis.
The above is the detailed content of the process steps of MyBatis-Plus based on MyBatis encapsulation BaseMapper. For more information about MyBatis-Plus encapsulation BaseMapper, please follow my other related articles!