MyBatis series (four)---configuration detailed typealiases alias (MyBatis source)

Source: Internet
Author: User

In the article "MyBatis Series (three)---configuration detailed properties and environments (MyBatis source article)" introduced the properties and environments, This article continues with one of the remaining configuration nodes: Typealiases. Typealiases node is mainly used to set aliases, in fact, this is a very useful feature, by configuring aliases, we do not have to specify the full package name, and can also take aliases.

For example: we are using com.demo.entity. Userentity, we can directly configure an alias user, so that later in the configuration file to use to com.demo.entity. When userentity, use the user directly.

For example, let's take a look at the configuration method of typealiases:

<Configuration><Typealiases>  through the package , you can specify the package name directly, MyBatis will automatically scan you to specify the JavaBean under the packet, and the default setting is an alias, the default name is: JavaBean's first lowercase unqualified class name as its alias. You can also customize aliases in JavaBean plus annotations @alias, for example: @Alias (user) <package name= "com.dy.entity"/> - -<typealias  Alias= "userentity"  type = "Com.dy.entity.User" /> </typealiases> </configuration                 

Write another test code to see if it's working: (I write only a pseudo-code)

Configuration con = sqlsessionfactory.getconfiguration (); map<string, class<?>> typemap = con.gettypealiasregistry (). gettypealiases ();
For (entry<string, class<?>> entry:typeMap.entrySet ()) { System.out.println (Entry.getkey () + "= = ==============> "+ Entry.getvalue (). Getsimplename ());
}

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

The above gives you a brief introduction of the use of typealiases, the next look at the source code in MyBatis:

The usual, first from the parsing of XML:

1/**2* Parse typealiases node3*/4PrivatevoidTypealiaseselement (xnode parent) {5if (Parent! =Null) {6For(XNode Child:parent.getChildren ()) {7//If the child node is a package, the Name property of the package node is obtained, and MyBatis scans the specified package8if ("Package". Equals (Child.getname ())) {9 String typealiaspackage = Child.getstringattribute ("name");10//Typealiasregistry is responsible for managing aliases, here is the alias registration through Typealiasregistry, the following will look at Typealiasregistry source11Configuration.gettypealiasregistry (). registeraliases (Typealiaspackage);12}Else{13//If the child node is a Typealias node, then the property value of the Alias property and type is obtainedString alias = Child.getstringattribute ("Alias");String type = Child.getstringattribute ("type");16Try{Class<?> Clazz =Resources.classforname (type);18if (alias = =Null) {19Typealiasregistry.registeralias (Clazz);20}Else {21 22 }23} catch (ClassNotFoundException e) {24 throw new builderexception ("Error Registering Typealias for '" + Alias + ".) Cause: "+ E, E); 25 }26 }27 }28 }29}            

The important source code is here:

Typealiasregistry:

PublicClassTypealiasregistry {//This is the core of Ah, the original alias is only through a hashmap to achieve, key is an alias, value is the type of the alias (class object)PrivateFinal map<string, class<?>> type_aliases =New Hashmap<string, class<?>>();/*** The following is the MyBatis default for our registered alias*/PublicTypealiasregistry () {Registeralias ("string", String.Class); Registeralias ("Byte", byte.Class); Registeralias ("Long", long.)Class); Registeralias ("short"), short.Class); Registeralias ("int", Integer.Class); Registeralias ("integer", Integer.Class); Registeralias ("Double", double.Class); Registeralias ("float", float.Class); Registeralias ("Boolean", Boolean.Class); Registeralias ("byte[]", byte[].Class); Registeralias ("long[]", long[].Class); Registeralias ("short[]", short[].Class); Registeralias ("int[]", integer[].Class); Registeralias ("integer[]", integer[].Class); Registeralias ("double[]", double[].Class); Registeralias ("float[]", float[].Class); Registeralias ("boolean[]", boolean[].Class); Registeralias ("_byte",Byte.Class); Registeralias ("_long",Long.Class); Registeralias ("_short",Short.Class); Registeralias ("_int",Int.Class); Registeralias ("_integer",Int.Class); Registeralias ("_double",Double.Class); Registeralias ("_float",Float.Class); Registeralias ("_boolean",Boolean.Class); Registeralias ("_byte[]",Byte[].Class); Registeralias ("_long[]",Long[].Class); Registeralias ("_short[]",Short[].Class); Registeralias ("_int[]",Int[].Class); Registeralias ("_integer[]",Int[].Class); Registeralias ("_double[]",Double[].Class); Registeralias ("_float[]",Float[].Class); Registeralias ("_boolean[]",Boolean[].Class); Registeralias ("date", date.)Class); Registeralias ("decimal", BigDecimal.Class); Registeralias ("BigDecimal", BigDecimal.Class); Registeralias ("BigInteger", BigInteger.Class); Registeralias ("Object", object.Class); Registeralias ("date[]", date[].Class); Registeralias ("decimal[]", bigdecimal[].Class); Registeralias ("bigdecimal[]", bigdecimal[].Class); Registeralias ("biginteger[]", biginteger[].Class); Registeralias ("object[]", object[].Class); Registeralias ("Map", map.Class); Registeralias ("HashMap", HashMap.Class); Registeralias ("list", list.Class); Registeralias ("ArrayList", ArrayList.Class); Registeralias ("Collection", collection.Class); Registeralias ("iterator", iterator.Class); Registeralias ("ResultSet", ResultSet.Class); }/*** Processing aliases, directly from the HashMap to save the alias can be removed*/@SuppressWarnings ("Unchecked")Public <T> class<t>Resolvealias (String string) {Try{if (string = =NullReturnNull; String key = String.tolowercase (Locale.english);//Issue #748 Class<t>ValueIf(Type_aliases.containskey (key)) {value = (class<t>) Type_aliases.get (key); }Else{value = (class<t>) Resources.classforname (string); }ReturnValue }Catch(ClassNotFoundException e) {ThrowNew Typeexception ("Could not resolve type alias '" + String + "'. Cause: "+E, E); } }/*** When configured as a package in the configuration file, this method will be called, according to the configuration of the registration to scan JavaBean, and then automatically register the alias * The default is to use the Bean's first lowercase unqualified class name as its alias * can also be added in JavaBean annotated @alias from the definition Name, for example: @Alias (user)*/PublicvoidRegisteraliases (String packagename) {registeraliases (PackageName, Object.Class); }Publicvoid Registeraliases (String packagename, class<?>supertype) {resolverutil<class<?>> Resolverutil =New resolverutil<class<?>>(); Resolverutil.find (NewResolverutil.isa (supertype), packagename); set<class<?Extends class<?>>> typeset =Resolverutil.getclasses ();for (class<?>Type:typeset) {//Ignore Inner classes and interfaces (including Package-info.java)//Skip also inner classes. See issue #6if (!type.isanonymousclass () &&!type.isinterface () &&!Type.ismemberclass ()) {Registeralias (type);}} }Publicvoid Registeralias (class<?>Type) {String alias =Type.getsimplename (); Alias aliasannotation = Type.getannotation (alias.Class);if (aliasannotation! =Null) {alias =Aliasannotation.value (); } registeralias (alias, type); }//This is the essential method of registering aliases, in fact, to save the alias of the HashMap new value-added, hehe, the implementation of the alias is too simple, right?public void Registeralias (String alias, class<?> value) {if (alias = = null) throw new Typeexception ("The parameter alias cannot be null"); String key = Alias.tolowercase (Locale.english); Issue #748 if (Type_aliases.containskey (key) && Type_aliases.get (key)! = NULL &&! Type_aliases.get (key). Equals (value) {throw new Typeexception ("the alias" + Alias + "is already mapped to the value") "+ type_aliases.get (key). GetName () +" '. "); Type_aliases.put (key, value); } public void Registeralias (string alias, String value) {try {Registeralias (alias, Resources.classforname (value));} Cat CH (classnotfoundexception e) {throw new Typeexception ("Error registering type alias" +alias+ "for" +value+ ". Cause: "+ E, E);}} /** * Gets the hashmap that holds the alias, the configuration object holds a reference to the typealiasregistry, so if necessary, we can get */public through the Configuration object map<string , class<?>> gettypealiases () {return collections.unmodifiablemap (type_aliases);}} 

From the source is visible, set the principle of the alias is so simple, mybatis default to US set a lot of aliases, in the above code can be seen.

Well, this is the easy part. The next article will continue to explain the configuration nodes that are not finished.

Original address: http://www.cnblogs.com/dongying/p/4037678.html

MyBatis series (four)---configuration detailed typealiases alias (MyBatis source)

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.