MyBatis series (five)---typehandler Introduction and configuration (MyBatis source) [Turn]

Source: Internet
Author: User

In the article "MyBatis Series (four)---configuration details of the typealiases alias (MyBatis source)" For you to introduce the use of aliases in MyBatis, as well as its source code. This article will introduce Typehandler for you, and simple analysis of its source code.

What is the Typehandler in MyBatis?

Whether MyBatis sets a parameter in a preprocessing statement (PreparedStatement) or extracts a value from the result set, the value obtained by the type processor is converted to the Java type in the appropriate way. MyBatis default for us to implement a lot of typehandler, when we do not configure the specified Typehandler, mybatis depending on the parameters or return the results of the difference, the default for us to choose the appropriate typehandler processing.

So, what Typehandler did MyBatis achieve for us?  How do we customize the implementation of a Typehandler? These will be seen in the source code of the next MyBatis.

Before looking at the source code, still like before, first look at how to configure it?

Configuration Typehandler:

<configuration>    <typeHandlers>      <!--           When the package is configured, MyBatis will go to the configured package scan Typehandler          <package name= "Com.dy.demo"/>            -<!--handler properties directly configure what we want to specify Typehandler-      < Typehandler handler= ""/>            <!--javatype configuration Java type, such as String, if it is with Javatype, the specified Typehandler will only be used for the specified type--      <typehandler javatype= "" handler= ""/>            <!--jdbctype metabase base data type, such as varchar, if jdbctype is fitted, Then the specified Typehandler is only used for the specified type  -      -<typehandler jdbctype= "handler=" "/>            <!--can also be configured for both-- >      <typehandler javatype= "" jdbctype= "" handler= ""/>        </typeHandlers>    ...  </configuration>

The above simply introduced a bit typehandler, the following look at MyBatis Typehandler source.

========================================================= I am the source split line =============================================== ===========

The usual, first from the parsing of XML:

/** * Parse typehandlers node */private void typehandlerelement (xnode parent) throws Exception {if (parent! = null) {fo R (XNode Child:parent.getChildren ()) {///child node is the package, gets the value of its Name property, and then automatically scans the custom Typehandler if ("Packa          GE ". Equals (Child.getname ())) {String typehandlerpackage = Child.getstringattribute (" name ");        Typehandlerregistry.register (Typehandlerpackage); If the else {//child node is Typehandler, you can specify the Javatype property, or you can specify Jdbctype, or both specify that the//javatype is the specified Java type//JDBC          Type is the specified JDBC type (database type: varchar) String javatypename = Child.getstringattribute ("Javatype");          String jdbctypename = Child.getstringattribute ("Jdbctype");          Handler is our configured Typehandler String handlertypename = Child.getstringattribute ("handler");          The Resolveclass method is the method class<?> Javatypeclass = Resolveclass (javatypename) of the typealiasregistry inside which we talked about in the last article.   Jdbctype is an enumeration type, and the Resolvejdbctype method is to get the value of the enumeration type       Jdbctype Jdbctype = Resolvejdbctype (jdbctypename);          class<?> Typehandlerclass = Resolveclass (handlertypename); Register Typehandler, Typehandler through Typehandlerregistry This class manages if (Javatypeclass! = null) {if (Jdbctype = = Nu            ll) {Typehandlerregistry.register (Javatypeclass, Typehandlerclass);            } else {typehandlerregistry.register (Javatypeclass, Jdbctype, Typehandlerclass);          }} else {typehandlerregistry.register (typehandlerclass); }        }      }    }}

Next look at Typehandler's management registration class:

Typehandlerregistry:

/** * Typehandler Registration Management Class */public final class Typehandlerregistry {//source one up, apart, a few big HashMap appeared, This is not the same as the last typealiases registration of the same///basic data type and its wrapper class private static final Map<class<?>, class<?>> Reverseprimitivemap = new Hashmap<class<?>, class<?>> () {private static final long Serialversionuid    = 1L;      {Put (byte.class, byte.class);      Put (Short.class, short.class);      Put (Integer.class, int.class);      Put (Long.class, long.class);      Put (Float.class, float.class);      Put (Double.class, double.class);      Put (Boolean.class, boolean.class);    Put (Character.class, char.class);  }  }; These maps don't have to know what's in store, the benefits of naming private final Map<jdbctype, typehandler<?>> jdbc_type_handler_map = new  Enummap<jdbctype, typehandler<?>> (Jdbctype.class); Private final Map<type, Map<jdbctype, typehandler<?>>> type_handler_map = new Hashmap<type, Map  <jdbctype, typehandler<?>>> (); Private Final Typehandler<object> Unknown_type_handler = new Unknowntypehandler (this); Private final map<class<?>, typehandler<?>> all_type_handlers_map = new Hashmap<class<?>,  Typehandler<?>> (); Like the typealiases in the previous article, MyBatis also defaults to us registering a lot of typehandler//specific as follows public Typehandlerregistry () {Register (Boolean.class    , new Booleantypehandler ());    Register (Boolean.class, new Booleantypehandler ());    Register (Jdbctype.boolean, new Booleantypehandler ());    Register (Jdbctype.bit, new Booleantypehandler ());    Register (Byte.class, new Bytetypehandler ());    Register (Byte.class, new Bytetypehandler ());    Register (Jdbctype.tinyint, new Bytetypehandler ());    Register (Short.class, new Shorttypehandler ());    Register (Short.class, new Shorttypehandler ());    Register (Jdbctype.smallint, new Shorttypehandler ());    Register (Integer.class, new Integertypehandler ());    Register (Int.class, new Integertypehandler ());   Register (Jdbctype.integer, new Integertypehandler ()); Register (Long.class, new Longtypehandler ());    Register (Long.class, new Longtypehandler ());    Register (Float.class, new Floattypehandler ());    Register (Float.class, new Floattypehandler ());    Register (Jdbctype.float, new Floattypehandler ());    Register (Double.class, new Doubletypehandler ());    Register (Double.class, new Doubletypehandler ());    Register (jdbctype.double, new Doubletypehandler ());    Register (String.class, new Stringtypehandler ());    Register (String.class, Jdbctype.char, New Stringtypehandler ());    Register (String.class, Jdbctype.clob, New Clobtypehandler ());    Register (String.class, Jdbctype.varchar, New Stringtypehandler ());    Register (String.class, Jdbctype.longvarchar, New Clobtypehandler ());    Register (String.class, Jdbctype.nvarchar, New Nstringtypehandler ());    Register (String.class, Jdbctype.nchar, New Nstringtypehandler ());    Register (String.class, Jdbctype.nclob, New Nclobtypehandler ());    Register (Jdbctype.char, new Stringtypehandler ()); RegiSter (Jdbctype.varchar, New Stringtypehandler ());    Register (Jdbctype.clob, new Clobtypehandler ());    Register (Jdbctype.longvarchar, new Clobtypehandler ());    Register (Jdbctype.nvarchar, new Nstringtypehandler ());    Register (Jdbctype.nchar, new Nstringtypehandler ());    Register (Jdbctype.nclob, new Nclobtypehandler ());    Register (Object.class, Jdbctype.array, New Arraytypehandler ());    Register (Jdbctype.array, new Arraytypehandler ());    Register (Biginteger.class, new Bigintegertypehandler ());    Register (Jdbctype.bigint, new Longtypehandler ());    Register (Bigdecimal.class, new Bigdecimaltypehandler ());    Register (Jdbctype.real, new Bigdecimaltypehandler ());    Register (Jdbctype.decimal, new Bigdecimaltypehandler ());    Register (Jdbctype.numeric, new Bigdecimaltypehandler ());    Register (Byte[].class, new Byteobjectarraytypehandler ());    Register (Byte[].class, Jdbctype.blob, New Blobbyteobjectarraytypehandler ()); Register (Byte[].class, jdbctype.longvarbinary, new BlobbyteobjEctarraytypehandler ());    Register (Byte[].class, new Bytearraytypehandler ());    Register (Byte[].class, Jdbctype.blob, New Blobtypehandler ());    Register (Byte[].class, jdbctype.longvarbinary, New Blobtypehandler ());    Register (jdbctype.longvarbinary, new Blobtypehandler ());    Register (Jdbctype.blob, new Blobtypehandler ());    Register (Object.class, Unknown_type_handler);    Register (Object.class, Jdbctype.other, Unknown_type_handler);    Register (Jdbctype.other, Unknown_type_handler);    Register (Date.class, new Datetypehandler ());    Register (Date.class, jdbctype.date, New Dateonlytypehandler ());    Register (Date.class, Jdbctype.time, New Timeonlytypehandler ());    Register (Jdbctype.timestamp, new Datetypehandler ());    Register (Jdbctype.date, new Dateonlytypehandler ());    Register (Jdbctype.time, new Timeonlytypehandler ());    Register (Java.sql.Date.class, new Sqldatetypehandler ());    Register (Java.sql.Time.class, new Sqltimetypehandler ()); Register (Java.sql.Timestamp.class,New Sqltimestamptypehandler ());    Issue #273 Register (Character.class, new Charactertypehandler ());  Register (Char.class, new Charactertypehandler ());  public boolean Hastypehandler (class<?> javatype) {return Hastypehandler (javatype, NULL); } public boolean Hastypehandler (typereference<?> javatypereference) {return Hastypehandler (javatypereference, n  ULL); } public boolean Hastypehandler (class<?> javatype, Jdbctype jdbctype) {return javatype! = null && getTy  Pehandler ((Type) Javatype, jdbctype)! = NULL; } public boolean Hastypehandler (typereference<?> javatypereference, Jdbctype jdbctype) {return Javatypereferenc  E! = null && gettypehandler (javatypereference, jdbctype)! = NULL; } public typehandler<?> Getmappingtypehandler (class<? extends typehandler<?>> Handlertype) {return  All_type_handlers_map.get (Handlertype); } public <T> typehandler<t> Gettypehandler (class<t> type) {    Return Gettypehandler ((type) type, NULL); } public <T> typehandler<t> Gettypehandler (typereference<t> javatypereference) {return Gettypehandl  ER (javatypereference, null);  } public typehandler<?> Gettypehandler (Jdbctype jdbctype) {return jdbc_type_handler_map.get (JdbcType); } public <T> typehandler<t> Gettypehandler (class<t> type, Jdbctype jdbctype) {return Gettypehandler  ((type) type, jdbctype);    } public <T> typehandler<t> Gettypehandler (typereference<t> javatypereference, Jdbctype JdbcType) {  Return Gettypehandler (Javatypereference.getrawtype (), jdbctype); } Private <T> typehandler<t> Gettypehandler (type type, Jdbctype jdbctype) {map<jdbctype, TYPEHANDLER&L t;?    >> Jdbchandlermap = Type_handler_map.get (TYPE);    Typehandler<?> handler = null;      if (jdbchandlermap! = null) {handler = Jdbchandlermap.get (Jdbctype); if (handler = = null) {handler = JdbchandLermap.get (NULL); }} if (handler = = NULL && type! = null && type instanceof Class && Enum.class.isAssignableF    Rom ((class<?>) type) {handler = new Enumtypehandler ((class<?>) type); } @SuppressWarnings ("Unchecked")//Type drives generics here typehandler<t> returned = (TYPEHANDLER&LT;T&G    t;) handler;  return returned;  } public typehandler<object> Getunknowntypehandler () {return unknown_type_handler; } public void register (Jdbctype jdbctype, typehandler<?> handler) {jdbc_type_handler_map.put (Jdbctype, handler)  ; }////REGISTER INSTANCE///** * Only configured with Typehandler, no configuration Jdbctype or Javatype/@SuppressWarnings ("unchecked") pu    Blic <T> void Register (typehandler<t> typehandler) {Boolean mappedtypefound = false; When customizing the Typehandler, you can add the annotation mappedtypes to specify the associated Javatype//So, here you need to scan mappedtypes annotations Mappedtypes mappedtypes = Typehandler . GetClass (). Getannotation (MAPPEDTYPES.CLASS); if (mappedtypes! = null) {for (class<?> HandledType:mappedTypes.value ()) {Register (Handledtype, type        Handler);      Mappedtypefound = true;  }}//@since 3.1.0-try to auto-discover the mapped type if (!mappedtypefound && typehandler instanceof        TypeReference) {try {typereference<t> typereference = (typereference<t>) Typehandler;        Register (Typereference.getrawtype (), Typehandler);      Mappedtypefound = true; } catch (Throwable t) {//Maybe users define the typereference with a different type and is not assignable, so Ju    St Ignore It} if (!mappedtypefound) {register ((class<t>) null, Typehandler); }}/** * configured with Typehandlerhe and Javatype */public <T> void Register (class<t> javatype, typehandler<? ext  Ends T> Typehandler) {register (Type) Javatype, Typehandler); } Private <T> void register (Type javatype, typehandler<? extendS t> typehandler) {//scan annotations mappedjdbctypes mappedjdbctypes mappedjdbctypes = Typehandler.getclass (). GetAnnotation (    Mappedjdbctypes.class); if (mappedjdbctypes! = null) {for (Jdbctype HandledJdbcType:mappedJdbcTypes.value ()) {Register (Javatype, h      Andledjdbctype, Typehandler);      } if (Mappedjdbctypes.includenulljdbctype ()) {register (javatype, NULL, Typehandler);    }} else {register (javatype, NULL, Typehandler);    }} public <T> void register (typereference<t> javatypereference, typehandler<? extends t> handler) {  Register (Javatypereference.getrawtype (), handler); }/** * Typehandlerhe, Javatype, Jdbctype are configured with */public <T> void Register (class<t> type, Jdbctype jdbctype , typehandler<?  Extends t> handler) {register (type) type, Jdbctype, handler); /** * The core method of registering a Typehandler * is to add data to the map * * * private void Register (Type javatype, Jdbctype Jdbctype, TYPEHANDLER&L t;?  > Handler) {  if (javatype! = null) {map<jdbctype, typehandler<?>> Map = Type_handler_map.get (Javatype);        if (map = = null) {map = new Hashmap<jdbctype, typehandler<?>> ();      Type_handler_map.put (Javatype, MAP);      } map.put (Jdbctype, handler);      if (Reverseprimitivemap.containskey (Javatype)) {Register (Reverseprimitivemap.get (javatype), Jdbctype, Handler);  }} all_type_handlers_map.put (Handler.getclass (), handler); }////REGISTER CLASS////Only handler type public void REGISTER (Class<?> typehandlerclass) {Boolean map    Pedtypefound = false;    Mappedtypes mappedtypes = typehandlerclass.getannotation (Mappedtypes.class); if (mappedtypes! = null) {for (class<?> JavaTypeClass:mappedTypes.value ()) {Register (Javatypeclass,        Typehandlerclass);      Mappedtypefound = true;    }} if (!mappedtypefound) {register (getinstance (null, typehandlerclass)); }}//Java type + handLer type public void register (class<?> javatypeclass, class<?> typehandlerclass) {register (Javatypeclass,  GetInstance (Javatypeclass, Typehandlerclass)); }//Java type + JDBC Type + handler type public void register (class<?> javatypeclass, Jdbctype Jdbctype, class&lt ;?  > Typehandlerclass) {register (Javatypeclass, Jdbctype, getinstance (Javatypeclass, Typehandlerclass));  }//Construct a handler (used also from Builders) @SuppressWarnings ("unchecked") public <T> typehandler<t>        getinstance (class<?> javatypeclass, class<?> typehandlerclass) {if (Javatypeclass! = null) {try {        constructor<?> C = typehandlerclass.getconstructor (Class.class);      Return (typehandler<t>) c.newinstance (Javatypeclass); } catch (Nosuchmethodexception ignored) {//ignored} catch (Exception e) {throw new Typeexception ("F      Ailed invoking constructor for handler "+ Typehandlerclass, E);    }    }try {constructor<?> c = typehandlerclass.getconstructor ();    Return (typehandler<t>) c.newinstance ();    } catch (Exception e) {throw new Typeexception ("Unable to find a usable constructor for" + Typehandlerclass, E); }}/** * Scans the custom Typehander according to the specified pacakge, then registers */public void Register (String packagename) {RESOLVERUTIL&LT;CL    ass<?>> resolverutil = new resolverutil<class<?>> ();    Resolverutil.find (New Resolverutil.isa (Typehandler.class), packagename); set<class<?    Extends class<?>>> Handlerset = resolverutil.getclasses (); for (class<?> type:handlerset) {//ignore inner classes and interfaces (including Package-info.java) and Abst Ract Classes if (!type.isanonymousclass () &&!type.isinterface () &&!      Modifier.isabstract (Type.getmodifiers ())) {register (type); }}}//Get information/** * can get all registered Typehandler */public Collect through the configuration objectIon<typehandler<?>> gettypehandlers () {return collections.unmodifiablecollection (ALL_TYPE_HANDLERS_  Map.values ()); }  }

From the source can see, mybatis for us to achieve so many typehandler, casually open a typehandler, see its source code, can see, it inherits from an abstract class: Basetypehandler, Can we also implement custom Typehandler by inheriting Basetypehandler? The answer is yes, so now let's show you the custom Typehandler:

===================================================== Custom Typehandler Split Line ========================================= ===================

Exampletypehandler:

@MappedJdbcTypes (Jdbctype.varchar)  
Here, if you do not specify Jdbctype with annotations, you can specify it in the configuration file through the "Jdbctype" attribute, and Javatype can also specify the public class by @MappedTypes Exampletypehandler Extends Basetypehandler<string> { @Override public void Setnonnullparameter (preparedstatement ps, int i , String parameter, Jdbctype jdbctype) throws SQLException { ps.setstring (i, parameter); } @Override public String Getnullableresult (ResultSet rs, String columnName) throws SQLException { return Rs.getstring (ColumnName); } @Override public String Getnullableresult (ResultSet rs, int columnindex) throws SQLException { return Rs.getstring (columnindex); } @Override public String Getnullableresult (callablestatement cs, int columnindex) throws SQLException { Return cs.getstring (columnindex);} }

Then, it's time to configure our custom Typehandler:

<configuration>  <typeHandlers>      <!--because the custom Typehandler has been specified by annotations at the time of definition, Jdbctype So there's no need to configure Jdbctype--      <typehandler handler= "Exampletypehandler"/>  </typeHandlers>    ......  </configuration>

That is, when we customize the Typehandler, we can specify the Jdbctype through the @mappedjdbctypes, by specifying the Javatype through the @MappedTypes, if not specified with annotations, Then we need to configure it in the configuration file.

Okay, here's the end of this article.

MyBatis series (five)---typehandler Introduction and configuration (MyBatis source) [Turn]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.