Home Java javaTutorial An in-depth explanation of the Mybatis series (3) - Detailed configuration of properties and environments (mybatis source code)

An in-depth explanation of the Mybatis series (3) - Detailed configuration of properties and environments (mybatis source code)

Mar 02, 2017 am 10:40 AM

In the previous article "In-depth introduction to the Mybatis series (2)---Configuration introduction (mybatis source code)", through a simple analysis of the mybatis source code, we can see that In the mybatis configuration file, in the configuration root node Below, you can configure the properties, typeAliases, plugins, objectFactory, objectWrapperFactory, settings, environments, databaseIdProvider, typeHandlers, and mappers nodes. So this time, we will first introduce the properties node and environments node.

In order to allow everyone to better read the mybatis source code, I will give you a simple example of how to use properties.

1 <configuration> 
2 <!-- 方法一: 从外部指定properties配置文件, 除了使用resource属性指定外,还可通过url属性指定url  
 3   <properties resource="dbConfig.properties"></properties> 
 4   --> 
 5   <!-- 方法二: 直接配置为xml --> 
 6   <properties> 
 7       <property name="driver" value="com.mysql.jdbc.Driver"/> 
 8       <property name="url" value="jdbc:mysql://localhost:3306/test1"/> 
 9       <property name="username" value="root"/>
 10       <property name="password" value="root"/>
 11   </properties>
Copy after login


So, if I use both methods at the same time, which method takes precedence?

When the above two methods are used, xml configuration takes priority, and externally specified properties configuration takes second place. As for why, the following source code analysis will mention it, please pay attention to it.

Let’s take a look at how to use the environments element node:

<environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          <!--
          如果上面没有指定数据库配置的properties文件,那么此处可以这样直接配置 
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>         -->
         
         <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
         <property name="driver" value="${driver}"/>
         <property name="url" value="${url}"/>
         <property name="username" value="${username}"/>
         <property name="password" value="${password}"/>
         
      </dataSource>
    </environment>
    
    <!-- 我再指定一个environment -->
    <environment id="test">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <!-- 与上面的url不一样 -->
        <property name="url" value="jdbc:mysql://localhost:3306/demo"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
    
  </environments>
Copy after login


The environments element node can be configured with multiple environment sub-nodes. How to understand it? ?

If the database used in the development environment of our system is different from the database used in the formal environment (this is for sure), then you can set up two environments, and the two IDs correspond to the development environment (dev) respectively. and formal environment (final), then you can select the corresponding environment by configuring the default attribute of environments. For example, if I configure the value of the default attribute of environments to dev, then the environment of dev will be selected. As for how this is implemented, the source code will be discussed below.

Okay, I briefly introduced the configuration of properties and environments above, and then we officially started to look at the source code:

Last time we said that mybatis is through XMLConfigBuilder. The class is parsing the mybatis configuration file, so this time we will take a look at XMLConfigBuilder’s parsing of properties and environments:

XMLConfigBuilder:

  1 public class XMLConfigBuilder extends BaseBuilder {  
  2   
  3     private boolean parsed;  
  4     //xml解析器  
  5     private XPathParser parser;  
  6     private String environment;  
  7     
  8     //上次说到这个方法是在解析mybatis配置文件中能配置的元素节点  
  9     //今天首先要看的就是properties节点和environments节点 
  10     private void parseConfiguration(XNode root) { 
  11         try { 
  12           //解析properties元素 
  13           propertiesElement(root.evalNode("properties")); //issue #117 read properties first 
  14           typeAliasesElement(root.evalNode("typeAliases")); 
  15           pluginElement(root.evalNode("plugins")); 
  16           objectFactoryElement(root.evalNode("objectFactory")); 
  17           objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); 
  18           settingsElement(root.evalNode("settings")); 
  19           //解析environments元素 
  20           environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631 
  21           databaseIdProviderElement(root.evalNode("databaseIdProvider")); 
  22           typeHandlerElement(root.evalNode("typeHandlers")); 
  23           mapperElement(root.evalNode("mappers")); 
  24         } catch (Exception e) { 
  25           throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); 
  26         } 
  27     } 
  28    
  29      
  30     //下面就看看解析properties的具体方法 
  31     private void propertiesElement(XNode context) throws Exception { 
  32         if (context != null) { 
  33           //将子节点的 name 以及value属性set进properties对象 
  34           //这儿可以注意一下顺序,xml配置优先, 外部指定properties配置其次 
  35           Properties defaults = context.getChildrenAsProperties(); 
  36           //获取properties节点上 resource属性的值 
  37           String resource = context.getStringAttribute("resource"); 
  38           //获取properties节点上 url属性的值, resource和url不能同时配置 
  39           String url = context.getStringAttribute("url"); 
  40           if (resource != null && url != null) { 
  41             throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other."); 
  42           } 
  43           //把解析出的properties文件set进Properties对象 
  44           if (resource != null) { 
  45             defaults.putAll(Resources.getResourceAsProperties(resource)); 
  46           } else if (url != null) { 
  47             defaults.putAll(Resources.getUrlAsProperties(url)); 
  48           } 
  49           //将configuration对象中已配置的Properties属性与刚刚解析的融合 
  50           //configuration这个对象会装载所解析mybatis配置文件的所有节点元素,以后也会频频提到这个对象 
  51           //既然configuration对象用有一系列的get/set方法, 那是否就标志着我们可以使用java代码直接配置? 
 52           //答案是肯定的, 不过使用配置文件进行配置,优势不言而喻 
 53           Properties vars = configuration.getVariables(); 
 54           if (vars != null) { 
 55             defaults.putAll(vars); 
 56           } 
 57           //把装有解析配置propertis对象set进解析器, 因为后面可能会用到 
 58           parser.setVariables(defaults); 
 59           //set进configuration对象 
 60           configuration.setVariables(defaults); 
 61         } 
 62     } 
 63      
 64     //下面再看看解析enviroments元素节点的方法 
 65     private void environmentsElement(XNode context) throws Exception { 
 66         if (context != null) { 
 67             if (environment == null) { 
 68                 //解析environments节点的default属性的值 
 69                 //例如: <environments default="development"> 
 70                 environment = context.getStringAttribute("default"); 
 71             } 
 72             //递归解析environments子节点 
 73             for (XNode child : context.getChildren()) { 
 74                 //<environment id="development">, 只有enviroment节点有id属性,那么这个属性有何作用? 
 75                 //environments 节点下可以拥有多个 environment子节点 
 76                 //类似于这样: <environments default="development"><environment id="development">...</environment><environment id="test">...</environments> 
 77                 //意思就是我们可以对应多个环境,比如开发环境,测试环境等, 由environments的default属性去选择对应的enviroment 
 78                 String id = child.getStringAttribute("id"); 
 79                 //isSpecial就是根据由environments的default属性去选择对应的enviroment 
 80                 if (isSpecifiedEnvironment(id)) { 
 81                     //事务, mybatis有两种:JDBC 和 MANAGED, 配置为JDBC则直接使用JDBC的事务,配置为MANAGED则是将事务托管给容器,  
 82                     TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager")); 
 83                     //enviroment节点下面就是dataSource节点了,解析dataSource节点(下面会贴出解析dataSource的具体方法) 
 84                     DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource")); 
 85                     DataSource dataSource = dsFactory.getDataSource(); 
 86                     Environment.Builder environmentBuilder = new Environment.Builder(id) 
 87                           .transactionFactory(txFactory) 
 88                           .dataSource(dataSource); 
 89                     //老规矩,会将dataSource设置进configuration对象 
 90                     configuration.setEnvironment(environmentBuilder.build()); 
 91                 } 
 92             } 
 93         } 
 94     } 
 95      
 96     //下面看看dataSource的解析方法 
 97     private DataSourceFactory dataSourceElement(XNode context) throws Exception { 
 98         if (context != null) { 
 99             //dataSource的连接池
 100             String type = context.getStringAttribute("type");
 101             //子节点 name, value属性set进一个properties对象
 102             Properties props = context.getChildrenAsProperties();
 103             //创建dataSourceFactory
 104             DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
 105             factory.setProperties(props);
 106             return factory;
 107         }
 108         throw new BuilderException("Environment declaration requires a DataSourceFactory.");
 109     } 
110 }
Copy after login


Through the above Interpretation of mybatis source code, I believe everyone has an in-depth understanding of the configuration of mybatis.

There is another question. We saw above that the expression ${driver} was used when configuring dataSource. How is this form parsed? In fact, it is parsed through the PropertyParser class:

PropertyParser:

/**
 * 这个类解析${}这种形式的表达式 */public class PropertyParser {  public static String parse(String string, Properties variables) {
    VariableTokenHandler handler = new VariableTokenHandler(variables);
    GenericTokenParser parser = new GenericTokenParser("${", "}", handler);    return parser.parse(string);
  }  private static class VariableTokenHandler implements TokenHandler {    private Properties variables;    public VariableTokenHandler(Properties variables) {      this.variables = variables;
    }    public String handleToken(String content) {      if (variables != null && variables.containsKey(content)) {        return variables.getProperty(content);
      }      return "${" + content + "}";
    }
  }
}
Copy after login


Okay, the above is the analysis of the properties and environments element nodes, which is more important. They are all marked in the comments on the source code. This article ends here, and the following articles will continue to analyze the configuration of other nodes.

The above is the content of the Mybatis series (3) - Detailed configuration of properties and environments (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)

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

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

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

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 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

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

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

See all articles