MyBatis.2剖析

JAVA就业套餐课:https://edu.csdn.net/combo/detail/1230

上次给大家介绍了一下properties 和 environments 的配置, 接下来就正式开始看源码了:

上次例子中,我们以 SqlSessionFactoryBuilder 去创建 SqlSessionFactory,  那么,我们就先从SqlSessionFactoryBuilder入手, 咱们先看看源码是怎么实现的:

SqlSessionFactoryBuilder源码片段:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

1 public class SqlSessionFactoryBuilder {

  2

  3   //Reader读取mybatis配置文件,传入构造方法

  4   //除了Reader外,其实还有对应的inputStream作为参数的构造方法,

  5   //这也体现了mybatis配置的灵活性

  6   public SqlSessionFactory build(Reader reader) {

  7     return build(reader, null null );

  8   }

  9

10   public SqlSessionFactory build(Reader reader, String environment) {

11     return build(reader, environment, null );

12   }

13  

14   //mybatis配置文件 + properties, 此时mybatis配置文件中可以不配置properties,也能使用${}形式

15   public SqlSessionFactory build(Reader reader, Properties properties) {

16     return build(reader, null , properties);

17   }

18  

19   //通过XMLConfigBuilder解析mybatis配置,然后创建SqlSessionFactory对象

20   public SqlSessionFactory build(Reader reader, String environment, Properties properties) {

21     try {

22       XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

23       //下面看看这个方法的源码

24       return build(parser.parse());

25     catch (Exception e) {

26       throw ExceptionFactory.wrapException( "Error building SqlSession." , e);

27     finally {

28       ErrorContext.instance().reset();

29       try {

30         reader.close();

31       catch (IOException e) {

32         // Intentionally ignore. Prefer previous error.

33       }

34     }

35   }

36

37   public SqlSessionFactory build(Configuration config) {

38     return new DefaultSqlSessionFactory(config);

39   }

40

41 }

通过源码,我们可以看到SqlSessionFactoryBuilder 通过XMLConfigBuilder 去解析我们传入的mybatis的配置文件, 下面就接着看看 XMLConfigBuilder 部分源码:

  我们说过mybatis 是通过XMLConfigBuilder这个类在解析mybatis配置文件的,那么本次就接着看看XMLConfigBuilder对于properties和environments的解析:

XMLConfigBuilder:

复制代码

1 public class XMLConfigBuilder extends BaseBuilder {23     private boolean parsed;4     //xml解析器5     private XPathParser parser;6     private String environment;78     //上次说到这个方法是在解析mybatis配置文件中能配置的元素节点9     //今天首先要看的就是properties节点和environments节点10     private void parseConfiguration(XNode root) {11         try {12           //解析properties元素13           propertiesElement(root.evalNode("properties")); //issue #117 read properties first14           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 #63121           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     }282930     //下面就看看解析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     }6364     //下面再看看解析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属性去选择对应的enviroment78                 String id = child.getStringAttribute("id");79                 //isSpecial就是根据由environments的default属性去选择对应的enviroment80                 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     }9596     //下面看看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             //创建dataSourceFactory104             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 }

复制代码

  通过以上对mybatis源码的解读,相信大家对mybatis的配置又有了一个深入的认识。

  还有一个问题, 上面我们看到,在配置dataSource的时候使用了 ${driver} 这种表达式, 这种形式是怎么解析的?其实,是通过PropertyParser这个类解析:

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 + "}";}}}

复制代码

好啦,以上就是对于properties 和 environments元素节点的分析,比较重要的都在对于源码的注释中标出。本次文章到此结束,接下来的文章会继续分析其他节点的配置。

通过以上源码,我们就能看出,在mybatis的配置文件中:

1. configuration节点为根节点。

2. 在configuration节点之下,我们可以配置10个子节点, 分别为:properties、typeAliases、plugins、objectFactory、objectWrapperFactory、settings、environments、databaseIdProvider、typeHandlers、mappers。

上次对于配置文件的方式是使用的是外部文件方式,如果不用外部文件,则可以使用下面的方式;

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>  	<environments default="development">  <environment id="development">  <transactionManager type="JDBC" />  <dataSource type="POOLED"> <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>			<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=mydb"/>			<property name="username" value="sa"/>			<property name="password" value="1"/></dataSource>  </environment> </environments>  <mappers>  <mapper resource="org/mybatis/example/dao/DeptMapper.xml"/>  </mappers>  </configuration>


猜你喜欢

转载自blog.51cto.com/2096101/2588291