SoFunction
Updated on 2025-04-13

MyBatis Methods to manage and find TypeHandlers

MyBatis byTypeHandlerRegistryComponents to centralizeManage and find TypeHandlerTypeHandlerYes 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

TypeHandlerRegistryIt 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 multipleMap) 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

TypeHandlerRegistryUse multiple internallyMapTo 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: TypeObject, representing Java type.
  • Inner Key: JdbcTypeEnumeration 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 firstTYPE_HANDLER_MAPDo a search.
  • Hierarchy structure: TYPE_HANDLER_MAPIt's a two-layer nestedMap. Outer layerMapThe key is Java type, inner layerMapThe 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 waysTypeHandlerRegistrymiddle:

3.1. XML configuration file ():

<typeHandlers>Elements and<typeHandler>Sub-elements:Use in the file<typeHandlers>Elements and<typeHandler>Child elements to register TypeHandler.

&lt;typeHandlers&gt;
    &lt;typeHandler javaType="" jdbcType="VARCHAR" handler=""/&gt;
    &lt;typeHandler package=""/&gt; &lt;!-- Scan package registration TypeHandler --&gt;
&lt;/typeHandlers&gt;
  • javaTypeProperties (optional): Specifies the Java type handled by TypeHandler. Multiple Java types can be specified, separated by commas.
  • jdbcTypeProperties (optional): Specifies the JDBC type handled by TypeHandler. Multiple JDBC types can be specified, separated by commas.
  • handlerProperty: 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.

XMLConfigBuilderAnalysis<typeHandlers>When elements are used, the configured TypeHandler will be registered withConfigurationThe object'stypeHandlerRegistrymiddle.

3.2. Java code configuration (Configuration object):

().register(...)Method: It can be passedConfigurationThe object'sgetTypeHandlerRegistry()Method GettingTypeHandlerRegistryInstance, 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@MappedTypesand@MappedJdbcTypesAnnotations 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 andTypeHandlerRegistrymiddle.
  • TypeHandler class needs to be used@MappedTypesand@MappedJdbcTypesAnnotation 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 inTypeHandlerRegistryIt will be automatically registered when initialized without explicit configuration. For example:StringTypeHandler, IntegerTypeHandler, DateTypeHandler, EnumTypeHandlerwait.

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 passTypeHandlerRegistryFind the right TypeHandler.TypeHandlerRegistryThe 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_MAPFind 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_MAPFind 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_HANDLERSFind TypeHandler in This approach is suitable for certain common JDBC type processing scenarios, such as handling allVARCHARTypes 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 searchListTypeHandler failed, MyBatis will try to findCollection, Iterable, ObjectTypeHandler 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.ObjectTypeHandlerCan be processedObjectTypes 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.
  • TypeHandlerInterface: The interface that all TypeHandler implementation classes need to implement, defines the method of type conversion (setParameter(), getResult()).
  • ConfigurationObject:TypeHandlerRegistryThe instance is stored inConfigurationin object.
  • XMLConfigBuilder: In analysisWhen the file,XMLConfigBuilderResponsible for analysis<typeHandlers>element and register the configured TypeHandler withConfigurationThe object'stypeHandlerRegistrymiddle.
  • JdbcTypeEnumeration: Defines the JDBC type constant.TypeInterface (Java Reflection API): Represents Java type.

Summarize

  • TypeHandlerRegistryThe role and TypeHandler management and search mechanism:
  • TypeHandlerRegistryIt 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.TypeHandlerRegistrymiddle.
  • TypeHandlerRegistryUsing multiple layersMapStructure 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 runtimeTypeHandlerRegistryFind the right TypeHandler and use the found TypeHandler to perform the type conversion operation.
  • TypeHandlerRegistryThe 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!