MyBatis byTypeHandlerRegistry
Components to centralizeManage and find TypeHandler。 TypeHandler
Yes used in MyBatisHandle conversion between Java types and JDBC typesimportant components. MyBatis requires managing a large number of TypeHandlers and being able to quickly find the right TypeHandler to perform type conversion as needed.
1. The role of TypeHandlerRegistry: TypeHandler registration center
TypeHandlerRegistry
It can be understood as in MyBatisTypeHandler's Registration CenterorTypeHandler's repository. Its core role is:
- Register TypeHandler:Responsible for registering various TypeHandlers into MyBatis systems. TypeHandler can be built-in with MyBatis or user-defined.
-
Storage TypeHandler:Maintain an internal data structure (actually multiple
Map
) to store registered TypeHandlers and organize them in different dimensions for easy search. - Find TypeHandler:Provides API methods that allow MyBatis to quickly find and obtain appropriate TypeHandler instances based on Java type and/or JDBC type at runtime.
2. TypeHandlerRegistry How to manage TypeHandler: Internal storage structure
TypeHandlerRegistry
Use multiple internallyMap
To store TypeHandlers, so as to search efficiently according to different search criteria. The main storage structures include:
KNOWN_TYPE_HANDLERS
(Map<JdbcType, TypeHandler<?>>):
- Key: JdbcType enum value, representing the JDBC type.
- Value: TypeHandler<?> instance.
- Function: Find TypeHandler according to JDBC type. For example, when MyBatis needs to process parameters or results of type VARCHAR, KNOWN_TYPE_HANDLERS is used to find the associated TypeHandler.
TYPE_HANDLER_MAP
(Map<Type, Map<JdbcType, TypeHandler<?>>>):
-
Outer Key:
Type
Object, representing Java type. -
Inner Key:
JdbcType
Enumeration value, representing JDBC type (can benull
, means that there is no distinction between JDBC types). -
Value:
TypeHandler<?>
Example. -
effect: Find TypeHandlers based on Java types and JDBC types.This is the most important TypeHandler storage and search structure. MyBatis will be used first
TYPE_HANDLER_MAP
Do a search. -
Hierarchy structure:
TYPE_HANDLER_MAP
It's a two-layer nestedMap
. Outer layerMap
The key is Java type, inner layerMap
The key is JDBC type. This structure allows precise search of TypeHandlers based on a combination of Java types and JDBC types.
ALL_TYPE_HANDLERS_MAP
(Map<Class<?>, TypeHandler<?>>):
-
Key:
Class<?>
Object, representing the Class type of TypeHandler. -
Value:
TypeHandler<?>
Example. -
effect: Find TypeHandler instances based on TypeHandler's Class type.Mainly used for passing
(Class<? extends TypeHandler> handlerType)
Methods directly search for instances based on TypeHandler type.
3. TypeHandler registration method:
TypeHandler can be registered in a variety of waysTypeHandlerRegistry
middle:
3.1. XML configuration file ():
<typeHandlers>
Elements and<typeHandler>
Sub-elements:Use in the file
<typeHandlers>
Elements and<typeHandler>
Child elements to register TypeHandler.
<typeHandlers> <typeHandler javaType="" jdbcType="VARCHAR" handler=""/> <typeHandler package=""/> <!-- Scan package registration TypeHandler --> </typeHandlers>
-
javaType
Properties (optional): Specifies the Java type handled by TypeHandler. Multiple Java types can be specified, separated by commas. -
jdbcType
Properties (optional): Specifies the JDBC type handled by TypeHandler. Multiple JDBC types can be specified, separated by commas. -
handler
Property: Specifies the fully qualified name of the TypeHandler implementation class. -
<typeHandler package="...">
: Specify the package name. MyBatis will scan all TypeHandlers under the specified package and automatically register.
XMLConfigBuilder
Analysis<typeHandlers>
When elements are used, the configured TypeHandler will be registered withConfiguration
The object'stypeHandlerRegistry
middle.
3.2. Java code configuration (Configuration object):
().register(...)
Method: It can be passedConfiguration
The object'sgetTypeHandlerRegistry()
Method GettingTypeHandlerRegistry
Instance, then useregister()
Method Manually register TypeHandler.
Configuration configuration = new Configuration(); TypeHandlerRegistry typeHandlerRegistry = (); (, , new MyStringTypeHandler()); // Register TypeHandler with specified Java type and JDBC type(); // Register TypeHandler, do not specify Java type and JDBC type (MyEnumTypeHandler requires @MappedTypes and @MappedJdbcTypes)(new MyDefaultTypeHandler()); // register TypeHandler Example,Not specified Java Types and JDBC type (MyDefaultTypeHandler Need to mark @MappedTypes and @MappedJdbcTypes)
-
register(TypeHandler<?> typeHandler)
: Register the TypeHandler instance. TypeHandler class needs to be used@MappedTypes
and@MappedJdbcTypes
Annotations specify the Java type and JDBC type it handles. -
register(Class<?> javaType, TypeHandler<?> typeHandler)
: Register an instance of TypeHandler of the specified Java type. -
register(JdbcType jdbcType, TypeHandler<?> typeHandler)
: Register an instance of TypeHandler of the specified JDBC type. -
register(Class<?> javaType, JdbcType jdbcType, TypeHandler<?> typeHandler)
: Register a TypeHandler instance that specifies Java type and JDBC type. -
register(String typeHandlerName)
: Register TypeHandler according to the alias of TypeHandler (the alias needs to be in<typeAliases>
defined in).
3.3. Automatically scan package (<typeHandlers package="...">):
- By
<typeHandlers>
Used in elements<typeHandler package="...">
A child element, you can specify the package name. MyBatis will automatically scan and register all TypeHandler implementation classes under the specified package and its subpackages andTypeHandlerRegistry
middle. - TypeHandler class needs to be used
@MappedTypes
and@MappedJdbcTypes
Annotation to declare the Java type and JDBC type it handles.
3.4. MyBatis built-in TypeHandler:
- The MyBatis framework has a large number of commonly used TypeHandlers built into it, which are used to handle conversions between Java basic types, commonly used Java types (such as String, Date, Enum) and JDBC types.
- These built-in TypeHandlers are in
TypeHandlerRegistry
It will be automatically registered when initialized without explicit configuration. For example:StringTypeHandler
,IntegerTypeHandler
,DateTypeHandler
,EnumTypeHandler
wait.
4. TypeHandlerRegistry How to find TypeHandler: Find policies
When MyBatis needs to perform type conversion (for example, set the PreparedStatement parameter to obtain the ResultSet result), it will passTypeHandlerRegistry
Find the right TypeHandler.TypeHandlerRegistry
The search strategy is as follows (priority from high to low):
4.1. Exactly match Java types and JDBC types:
MyBatis will try firstExact combination of Java type and JDBC typeexistTYPE_HANDLER_MAP
Find TypeHandler in This is the most accurate way to find it, if found, use the TypeHandler directly.
4.2. Match Java types and ignore JDBC types:
If the exact match between Java and JDBC types is not found, MyBatis will tryBased on Java type onlyexistTYPE_HANDLER_MAP
Find TypeHandler (JDBC type is set tonull
). This approach is suitable for some TypeHandlers that only need to be processed according to Java types, without distinguishing between JDBC types.
4.3. Search according to JDBC type:
If you cannot find a suitable TypeHandler based on both Java type and JDBC type, MyBatis will tryBy JDBC TypeexistKNOWN_TYPE_HANDLERS
Find TypeHandler in This approach is suitable for certain common JDBC type processing scenarios, such as handling allVARCHAR
Types of data can be used withThe associated TypeHandler.
4.4. Type Hierarchy:
If the above methods cannot find the appropriate TypeHandler, MyBatis will alsoConsider the inheritance relationship of Java types. For example, if searchList
TypeHandler failed, MyBatis will try to findCollection
, Iterable
, Object
TypeHandler of parent type or interface. This method can improve the versatility of TypeHandler.
4.5. Default TypeHandler (Default TypeHandler):
If you cannot find a suitable TypeHandler through all the search strategies mentioned above, MyBatis willUse the defaultObjectTypeHandler
(or other default TypeHandler)Perform processing.ObjectTypeHandler
Can be processedObject
Types of data, but type information may be lost and performance may be low.
5. Key components and classes:
-
TypeHandlerRegistry
: TypeHandler Registration Center, responsible for managing and finding TypeHandlers. -
TypeHandler
Interface: The interface that all TypeHandler implementation classes need to implement, defines the method of type conversion (setParameter()
,getResult()
). -
Configuration
Object:TypeHandlerRegistry
The instance is stored inConfiguration
in object. -
XMLConfigBuilder
: In analysisWhen the file,
XMLConfigBuilder
Responsible for analysis<typeHandlers>
element and register the configured TypeHandler withConfiguration
The object'stypeHandlerRegistry
middle. -
JdbcType
Enumeration: Defines the JDBC type constant.Type
Interface (Java Reflection API): Represents Java type.
Summarize
-
TypeHandlerRegistry
The role and TypeHandler management and search mechanism: -
TypeHandlerRegistry
It is the registration center for TypeHandler in MyBatis, which is responsible for managing and maintaining all registered TypeHandlers. TypeHandler can be registered in various ways such as XML configuration, Java code configuration, automatic package scanning and MyBatis built-in.TypeHandlerRegistry
middle. -
TypeHandlerRegistry
Using multiple layersMap
Structure stores TypeHandlers and provides efficient search strategies. You can find suitable TypeHandlers based on conditions such as Java types, JDBC types and type inheritance relationships. MyBatis will delegate when type conversion is required at runtimeTypeHandlerRegistry
Find the right TypeHandler and use the found TypeHandler to perform the type conversion operation. -
TypeHandlerRegistry
The management and search mechanism ensures that MyBatis can flexibly and efficiently handle conversions between various Java types and JDBC types, realizing the decoupling and scalability of type conversion.
This is the end of this article about MyBatis management and searching for TypeHandler. For more related contents of MyBatis to search for TypeHandler, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!