Home Java javaTutorial An in-depth explanation of the Mybatis series (4)---detailed configuration of typeAliases aliases (mybatis source code)

An in-depth explanation of the Mybatis series (4)---detailed configuration of typeAliases aliases (mybatis source code)

Mar 02, 2017 am 10:44 AM

The previous article "In-depth introduction to Mybatis series (3)---Detailed configuration of properties and environments (mybatis source code)" introduced properties and environments. This article continues to talk about one of the remaining configuration nodes: typeAliases. The typeAliases node is mainly used to set aliases. In fact, this is a very useful function. By configuring aliases, we no longer need to specify the complete package name, and can also take aliases.

For example: When we use com.demo.entity.UserEntity, we can directly configure an alias user, so that when we use com.demo.entity.UserEntity in the configuration file in the future, we can use it directly Just User.

Taking the above example as an example, let’s implement it and see how typeAliases is configured:

<configuration>
    <typeAliases>
      <!--
      通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean,
      并且默认设置一个别名,默认的名字为: javabean 的首字母小写的非限定类名来作为它的别名。
      也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user) 
      <package name="com.dy.entity"/>       -->
      <typeAlias alias="UserEntity" type="com.dy.entity.User"/>
  </typeAliases>
  
  ......  
</configuration>
Copy after login

Write another test code to see if it takes effect: (I only write a pseudocode )

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());
}
Copy after login

========================================== I am the source code Dividing line==============================================

The above gives you a brief introduction to the usage of typeAliases. Next, let’s take a look at the source code in Mybatis:

Old rules, let’s start with the parsing of xml:

 1 /** 
 2  * 解析typeAliases节点 
 3  */ 
 4 private void typeAliasesElement(XNode parent) {
 5     if (parent != null) { 
 6       for (XNode child : parent.getChildren()) { 
 7         //如果子节点是package, 那么就获取package节点的name属性, mybatis会扫描指定的package 
 8         if ("package".equals(child.getName())) { 
 9           String typeAliasPackage = child.getStringAttribute("name");
 10           //TypeAliasRegistry 负责管理别名, 这儿就是通过TypeAliasRegistry 进行别名注册, 下面就会看看TypeAliasRegistry源码
 11           configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
 12         } else {
 13           //如果子节点是typeAlias节点,那么就获取alias属性和type的属性值
 14           String alias = child.getStringAttribute("alias");
 15           String type = child.getStringAttribute("type");
 16           try {
 17             Class<?> clazz = Resources.classForName(type);
 18             if (alias == null) {
 19               typeAliasRegistry.registerAlias(clazz);
 20             } else {
 21               typeAliasRegistry.registerAlias(alias, clazz);
 22             }
 23           } catch (ClassNotFoundException e) {
 24             throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
 25           }
 26         }
 27       }
 28     }
 29   }
Copy after login


The important source code is here:

TypeAliasRegistry:

public class TypeAliasRegistry {  
  //这就是核心所在啊, 原来别名就仅仅通过一个HashMap来实现, key为别名, value就是别名对应的类型(class对象)
  private final Map<String, Class<?>> TYPE_ALIASES = new HashMap<String, Class<?>>();  /**
   * 以下就是mybatis默认为我们注册的别名   */
  public TypeAliasRegistry() {
    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);
  }  
  /**
   * 处理别名, 直接从保存有别名的hashMap中取出即可   */
  @SuppressWarnings("unchecked")  public <T> Class<T> resolveAlias(String string) {    
  try {      
  if (string == null) return null;
      String key = string.toLowerCase(Locale.ENGLISH); // issue #748
      Class<T> value;      if (TYPE_ALIASES.containsKey(key)) {
        value = (Class<T>) TYPE_ALIASES.get(key);
      } else {
        value = (Class<T>) Resources.classForName(string);
      }      return value;
    } catch (ClassNotFoundException e) {      
    throw new TypeException("Could not resolve type alias &#39;" + string + "&#39;.  Cause: " + e, e);
    }
  }  
  /**
   * 配置文件中配置为package的时候, 会调用此方法,根据配置的报名去扫描javabean ,然后自动注册别名
   * 默认会使用 Bean 的首字母小写的非限定类名来作为它的别名
   * 也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user)   */
  public void registerAliases(String packageName){
    registerAliases(packageName, Object.class);
  }  public void registerAliases(String packageName, Class<?> superType){
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
    resolverUtil.find(new ResolverUtil.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 #6
      if (!type.isAnonymousClass() && !type.isInterface() && !type.isMemberClass()) {
        registerAlias(type);
      }
    }
  }  public void registerAlias(Class<?> type) {
    String alias = type.getSimpleName();
    Alias aliasAnnotation = type.getAnnotation(Alias.class);    
    if (aliasAnnotation != null) {
      alias = aliasAnnotation.value();
    } 
    registerAlias(alias, type);
  }  //这就是注册别名的本质方法, 其实就是向保存别名的hashMap新增值而已, 呵呵, 别名的实现太简单了,对吧
  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 &#39;" + alias + "&#39; is already mapped to the value &#39;" + TYPE_ALIASES.get(key).getName() + "&#39;.");
    }
    TYPE_ALIASES.put(key, value);
  }  public void registerAlias(String alias, String value) {    try {
      registerAlias(alias, Resources.classForName(value));
    } catch (ClassNotFoundException e) {      
    throw new TypeException("Error registering type alias "+alias+" for "+value+". Cause: " + e, e);
    }
  }  
  /**
   * 获取保存别名的HashMap, Configuration对象持有对TypeAliasRegistry的引用,因此,如果需要,我们可以通过Configuration对象获取   */
  public Map<String, Class<?>> getTypeAliases() {    
  return Collections.unmodifiableMap(TYPE_ALIASES);
  }
}
Copy after login

It can be seen from the source code that the principle of setting alias is so simple. Mybatis sets it for us by default. There are many aliases, which can be seen in the above code.

Okay, the content of this article is that simple, that’s it. The next article will continue to explain the configuration nodes that have not been finished yet.

The above is the content of the Mybatis series (4) in simple terms---detailed configuration of typeAliases aliases (mybatis source code). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
iBatis vs. MyBatis: Which one is better for you? iBatis vs. MyBatis: Which one is better for you? Feb 19, 2024 pm 04:38 PM

iBatis vs. MyBatis: Which should you choose? Introduction: With the rapid development of the Java language, many persistence frameworks have emerged. iBatis and MyBatis are two popular persistence frameworks, both of which provide a simple and efficient data access solution. This article will introduce the features and advantages of iBatis and MyBatis, and give some specific code examples to help you choose the appropriate framework. Introduction to iBatis: iBatis is an open source persistence framework

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Various ways to implement batch deletion operations in MyBatis Various ways to implement batch deletion operations in MyBatis Feb 19, 2024 pm 07:31 PM

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

Detailed explanation of how to use MyBatis batch delete statements Detailed explanation of how to use MyBatis batch delete statements Feb 20, 2024 am 08:31 AM

Detailed explanation of how to use MyBatis batch delete statements requires specific code examples. Introduction: MyBatis is an excellent persistence layer framework that provides rich SQL operation functions. In actual project development, we often encounter situations where data needs to be deleted in batches. This article will introduce in detail how to use MyBatis batch delete statements, and attach specific code examples. Usage scenario: When deleting a large amount of data in the database, it is inefficient to execute the delete statements one by one. At this point, you can use the batch deletion function of MyBatis

Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Feb 23, 2024 pm 04:09 PM

Detailed explanation of MyBatis caching mechanism: One article to understand the principle of cache storage Introduction When using MyBatis for database access, caching is a very important mechanism, which can effectively reduce access to the database and improve system performance. This article will introduce the caching mechanism of MyBatis in detail, including cache classification, storage principles and specific code examples. 1. Cache classification MyBatis cache is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache. When

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

In-depth understanding of the batch Insert implementation principle in MyBatis In-depth understanding of the batch Insert implementation principle in MyBatis Feb 21, 2024 pm 04:42 PM

MyBatis is a popular Java persistence layer framework that is widely used in various Java projects. Among them, batch insertion is a common operation that can effectively improve the performance of database operations. This article will deeply explore the implementation principle of batch Insert in MyBatis, and analyze it in detail with specific code examples. Batch Insert in MyBatis In MyBatis, batch Insert operations are usually implemented using dynamic SQL. By constructing a line S containing multiple inserted values

See all articles