前言
每個基于Mybatis的應用都是以一個SqlSessionFactory實例為核心的。
生命周期和作用域
依賴注入框架可以創建線程安全的、基于事務的 SqlSession 和映射器,并將它們直接注入到你的 bean 中,因此可以直接忽略它們的生命周期。
-
非依賴注入框架下使用
生命周期和作用域.png
一、全局配置文件
參考網站:https://mybatis.org/mybatis-3/zh/configuration.html
MyBatis 的配置文件包含了會深深影響 MyBatis 行為的設置和屬性信息。 配置文檔的頂層結構如下
1. properties(屬性)
- 這些屬性可以在外部進行配置,并可以進行動態替換。你既可以在典型的 Java 屬性文件中配置這些屬性,也可以在 properties 元素的子元素中設置。
例如:
<!-- resource屬性:引入類路徑下的配置文件
url屬性:引入網絡或磁盤上的配置文件 -->
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="ceshi"/>
<property name="password" value="123456"/>
</properties>
- 設置好的屬性可以在整個配置文件中用來替換需要動態配置的屬性值。
比如:
<dataSource type="POOLED">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
如果一個屬性在不只一個地方進行了配置,那么,通過方法參數傳遞的屬性具有最高優先級,resource/url 屬性中指定的配置文件次之,最低優先級的則是 properties 元素中指定的屬性。
從 MyBatis 3.4.2 開始,你可以為占位符指定一個默認值(這個特性默認是關閉的。要啟用這個特性,需要添加一個特定的屬性來開啟這個特性)。
例如:
<properties resource="org/mybatis/example/config.properties">
<!-- 啟用默認值特性 -->
<property name="org.apache.ibatis.parsing.PropertyParser.enable-default-value" value="true"/>
</properties>
<dataSource type="POOLED">
<!-- 如果屬性 'username' 沒有被配置,'username' 屬性的值將為 'cs_user' -->
<property name="username" value="${username:cs_user}"/>
</dataSource>
如果你在屬性名中使用了 ":" 字符(如:db:username),或者在 SQL 映射中使用了 OGNL 表達式的三元運算符(如: ${tableName != null ? tableName : 'global_constants'}),就需要設置特定的屬性來修改分隔屬性名和默認值的字符。
例如:
<properties resource="org/mybatis/example/config.properties">
<!-- 修改默認值的分隔符 ?:-->
<property name="org.apache.ibatis.parsing.PropertyParser.default-value-separator" value="?:"/>
</properties>
<dataSource type="POOLED">
<property name="username" value="${db:username?:cs_user}"/>
</dataSource>
2.settings(設置)
MyBatis 中極為重要的調整設置,它們會改變 MyBatis 的運行時行為。
- 一個配置完整的 settings 元素的示例如下:
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
-
各項設置的含義及默認值
各項設置的含義、默認值.png
3.typeAliases(類型別名)
類型別名可為 Java 類型設置一個縮寫名字。 它僅用于 XML 配置,意在降低冗余的全限定類名書寫。(簡化映射文件中parameterType和ResultType中的POJO類型名稱編寫,默認支持別名)
例如:
<typeAliases>
<!-- 當這樣配置時,A01可以用在任何使用com.business.A01的地方。-->
<typeAlias alias="A01" type="com.business.A01"/>
<typeAlias alias="A02" type="com.business.A02"/>
</typeAliases>
也可以指定一個包名,MyBatis 會在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<!-- 每一個在包 com.business中的 Java Bean,在沒有注解的情況下,會使用 Bean 的首字母小寫的非限定類名來作為它的別名。 比如 com.business.A01 的別名為 a01; -->
<package name="com.business"/>
</typeAliases>
若有注解,則別名為其注解值。比如:
@Alias("a01")
public class A01 {
...
}
常見的 Java 類型內建的類型別名,它們都是不區分大小寫的,注意,為了應對原始類型的命名重復,采取了特殊的命名風格。
如:_byte/byte( 別名/映射文件);byte/Byte;hashmap/HashMap等。
4.typeHandlers(類型處理器)
MyBatis 在設置預處理語句(PreparedStatement)中的參數或從結果集中取出一個值時, 都會用類型處理器將獲取到的值以合適的方式轉換成 Java 類型(從 3.4.5 開始,MyBatis 默認支持 JSR-310(日期和時間 API))。下表描述了一些默認的類型處理器。
也可以重寫已有的類型處理器或創建自定義的處理器來處理不支持或非標準的類型。實現必須遵循:實現org.apache.ibatis.type.TypeHandler接口,或繼承一個和便利的類org.apache.ibatis.type.BaseTypeHandler,并可將它映射到一個JDBC類型。
<typeHandlers>
<typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>
5.objectFactory(對象工廠)
每次MyBatis創建結果對象的新實例時,它都會使用一個對象工廠(ObjectFactory)實例來完成實例化工作。默認的對象工廠需要做的僅僅是實例化目標類,要么通過默認無參構造方法,要么通過已存在的參數映射來調用帶有參數的構造方法。也可以創建自己的對象工廠來覆蓋默認的。
比如:
// ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
public Object create(Class type) {
return super.create(type);
}
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
return super.create(type, constructorArgTypes, constructorArgs);
}
public void setProperties(Properties properties) {
super.setProperties(properties);
}
public <T> boolean isCollection(Class<T> type) {
return Collection.class.isAssignableFrom(type);
}}
<!-- mybatis-config.xml -->
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
<property name="someProperty" value="100"/>
</objectFactory>
ObjectFactory接口很簡單,他包含兩個創建實例用的方法,一是處理默認無參構造方法,另一個是處理待參數的構造方法。另外setProperties方法也可以被用來配置ObjectFactory,在初始化你的ObjectFactory實例后,objectFactory元素體定義的屬性會被傳遞給setProperties方法。
6.plugins(插件)
MyBatis 允許你在映射語句執行過程中的某一點進行攔截調用。默認情況下,MyBatis 允許使用插件來攔截的方法調用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
使用插件需特別注意,這些都是更底層的類和方法,試圖修改或重寫已有方法可能會破壞MyBatis的核心模塊。
通過MyBatis提供的強大機制,使用插件非常簡單,只需實現Interceptor接口,并指定想要攔截的方法簽名即可。
// ExamplePlugin.java 該插件將會攔截在 Executor 實例中所有的 “update” 方法調用, 這里的 Executor 是負責執行底層映射語句的內部對象。
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
private Properties properties = new Properties();
public Object intercept(Invocation invocation) throws Throwable {
// implement pre processing if need
Object returnObject = invocation.proceed();
// implement post processing if need
return returnObject;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
<!-- mybatis-config.xml -->
<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</plugin>
</plugins>
除了用插件來修改 MyBatis 核心行為以外,還可以通過完全覆蓋配置類來達到目的。只需繼承配置類后覆蓋其中的某個方法,再把它傳遞到 SqlSessionFactoryBuilder.build(myConfig) 方法即可。
7.environments(環境配置)
MyBatis 可以配置成適應多種環境,這種機制有助于將 SQL 映射應用于多種數據庫之中, 現實情況下有多種理由需要這么做。例如,開發、測試和生產環境需要有不同的配置;或者想在具有相同 Schema 的多個生產數據庫中使用相同的 SQL 映射。還有許多類似的使用場景。
不過要記住:盡管可以配置多個環境,但每個 SqlSessionFactory 實例只能選擇一種環境。
所以,如果你想連接兩個數據庫,就需要創建兩個 SqlSessionFactory 實例,每個數據庫對應一個。而如果是三個數據庫,就需要三個實例,依此類推,記起來很簡單:
-
每個數據庫對應一個 SqlSessionFactory 實例
為了指定創建哪種環境,只要將它作為可選的參數傳遞給 SqlSessionFactoryBuilder 即可。可以接受環境配置的兩個方法簽名是:
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);
如果忽略了環境參數,那么將會加載默認環境,如下所示:
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, properties);
environments 元素定義了如何配置環境。
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
注意一些關鍵點:
- 默認使用的環境 ID(比如:default="development")。
- 每個 environment 元素定義的環境 ID(比如:id="development")。
- 事務管理器的配置(比如:type="JDBC")。
- 數據源的配置(比如:type="POOLED")。
環境可以隨意命名,但務必保證默認的環境 ID 要匹配其中一個環境 ID。
transactionManager(事務管理器)
在 MyBatis 中有兩種類型的事務管理器(也就是 type="[JDBC|MANAGED]"):
- JDBC – 這個配置直接使用了 JDBC 的提交和回滾設施,它依賴從數據源獲得的連接來管理事務作用域。
- MANAGED – 這個配置幾乎沒做什么。它從不提交或回滾一個連接,而是讓容器來管理事務的整個生命周期(比如 JEE 應用服務器的上下文)。 默認情況下它會關閉連接。然而一些容器并不希望連接被關閉,因此需要將 closeConnection 屬性設置為 false 來阻止默認的關閉行為。例如:
<transactionManager type="MANAGED">
<property name="closeConnection" value="false"/>
</transactionManager>
如果你正在使用 Spring + MyBatis,則沒有必要配置事務管理器,因為 Spring 模塊會使用自帶的管理器來覆蓋前面的配置。
這兩種事務管理器類型都不需要設置任何屬性。它們其實是類型別名,換句話說,你可以用 TransactionFactory 接口實現類的全限定名或類型別名代替它們。
public interface TransactionFactory {
default void setProperties(Properties props) { // 從 3.5.2 開始,該方法為默認方法
// 空實現
}
Transaction newTransaction(Connection conn);
Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);
}
在事務管理器實例化后,所有在 XML 中配置的屬性將會被傳遞給 setProperties() 方法。你的實現還需要創建一個 Transaction 接口的實現類,這個接口也很簡單:
public interface Transaction {
Connection getConnection() throws SQLException;
void commit() throws SQLException;
void rollback() throws SQLException;
void close() throws SQLException;
Integer getTimeout() throws SQLException;
}
使用這兩個接口,你可以完全自定義 MyBatis 對事務的處理。
dataSource(數據源)
dataSource 元素使用標準的 JDBC 數據源接口來配置 JDBC 連接對象的資源。
-
大多數 MyBatis 應用程序會按示例中的例子來配置數據源。雖然數據源配置是可選的,但如果要啟用延遲加載特性,就必須配置數據源。
有三種內建的數據源類型(也就是 type="[UNPOOLED|POOLED|JNDI]"):
三種內建的數據源類型.png
可以通過實現接口 org.apache.ibatis.datasource.DataSourceFactory 來使用第三方數據源實現:
public interface DataSourceFactory {
void setProperties(Properties props);
DataSource getDataSource();
}
org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory 可被用作父類來構建新的數據源適配器,比如下面這段插入 C3P0 數據源所必需的代碼:
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0DataSourceFactory extends UnpooledDataSourceFactory {
public C3P0DataSourceFactory() {
this.dataSource = new ComboPooledDataSource();
}
}
為了令其工作,記得在配置文件中為每個希望 MyBatis 調用的 setter 方法增加對應的屬性。 下面是一個可以連接至 PostgreSQL 數據庫的例子:
<dataSource type="org.myproject.C3P0DataSourceFactory">
<property name="driver" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql:mydb"/>
<property name="username" value="postgres"/>
<property name="password" value="root"/>
</dataSource>
8.databaseIdProvider(數據庫廠商標識)
MyBatis 可以根據不同的數據庫廠商執行不同的語句,這種多廠商的支持是基于映射語句中的 databaseId 屬性。 MyBatis 會加載帶有匹配當前數據庫 databaseId 屬性和所有不帶 databaseId 屬性的語句。 如果同時找到帶有 databaseId 和不帶 databaseId 的相同語句,則后者會被舍棄。 為支持多廠商特性,只要像下面這樣在 mybatis-config.xml 文件中加入 databaseIdProvider 即可:
<databaseIdProvider type="DB_VENDOR" />
databaseIdProvider 對應的 DB_VENDOR 實現會將 databaseId 設置為 DatabaseMetaData#getDatabaseProductName() 返回的字符串。 由于通常情況下這些字符串都非常長,而且相同產品的不同版本會返回不同的值,你可能想通過設置屬性別名來使其變短:
<databaseIdProvider type="DB_VENDOR">
<property name="SQL Server" value="sqlserver"/>
<property name="DB2" value="db2"/>
<property name="Oracle" value="oracle" />
</databaseIdProvider>
在提供了屬性別名時,databaseIdProvider 的 DB_VENDOR 實現會將 databaseId 設置為數據庫產品名與屬性中的名稱第一個相匹配的值,如果沒有匹配的屬性,將會設置為 “null”。 在這個例子中,如果 getDatabaseProductName() 返回“Oracle (DataDirect)”,databaseId 將被設置為“oracle”。
你可以通過實現接口 org.apache.ibatis.mapping.DatabaseIdProvider 并在 mybatis-config.xml 中注冊來構建自己的 DatabaseIdProvider:
public interface DatabaseIdProvider {
default void setProperties(Properties p) { // 從 3.5.2 開始,該方法為默認方法
// 空實現
}
String getDatabaseId(DataSource dataSource) throws SQLException;
}
9.mappers(映射文件)
既然 MyBatis 的行為已經由上述元素配置完了,我們現在就要來定義 SQL 映射語句了。 但首先,我們需要告訴 MyBatis 到哪里去找到這些語句。 在自動查找資源方面,Java 并沒有提供一個很好的解決方案,所以最好的辦法是直接告訴 MyBatis 到哪里去找映射文件。 你可以使用相對于類路徑的資源引用,或完全限定資源定位符(包括 file:/// 形式的 URL),或類名和包名等。例如:
<!-- 使用相對于類路徑的資源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/A01Mapper.xml"/>
<mapper resource="org/mybatis/builder/B01Mapper.xml"/>
</mappers>
<!-- 使用完全限定資源定位符(URL) -->
<mappers>
<mapper url="file:///var/mappers/A01Mapper.xml"/>
<mapper url="file:///var/mappers/B01Mapper.xml"/>
</mappers>
<!-- 使用映射器接口實現類的完全限定類名 -->
<mappers>
<mapper class="org.mybatis.builder.A01Mapper"/>
<mapper class="org.mybatis.builder.B01Mapper"/>
</mappers>
<!-- 將包內的映射器接口實現全部注冊為映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
細節將在映射文件加載流程中會詳細談。
二、重要類與對象說明
-
SqlSessionFactoryBuilder
SqlSessionFactoryBuilder 有9種build() 方法,每一種都允許你從不同的資源中創建一個 SqlSessionFactory 實例。
public SqlSessionFactory build(Reader reader);
public SqlSessionFactory build(Reader reader, String environment);
public SqlSessionFactory build(Reader reader, Properties properties);
public SqlSessionFactory build(Reader reader, String environment, Properties properties);
public SqlSessionFactory build(InputStream inputStream);
public SqlSessionFactory build(InputStream inputStream, String environment);
public SqlSessionFactory build(InputStream inputStream, Properties properties);
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) ;
public SqlSessionFactory build(Configuration config);
-
XMLConfigBuilder
專門用來解析全局配置文件的解析器
-
XpathParser
使用XPATH解析XML配置文件
-
Configuration對象
MyBatis框架支持開發人員通過配置文件與其進行交流.在配置文件所配置的信息,在框架運行時,會被XMLConfigBuilder解析并存儲在一個Configuration對象中.Configuration對象會被作為參數傳送給DeFaultSqlSessionFactory.而DeFaultSqlSessionFactory根據Configuration對象信息為Client創建對應特征的SqlSession對象(Configuration 類包含了對一個 SqlSessionFactory 實例你可能關心的所有內容)。
protected Environment environment;
// 允許在嵌套語句中使用分頁(RowBounds)。如果允許使用則設置為false。默認為false
protected boolean safeRowBoundsEnabled;
// 允許在嵌套語句中使用分頁(ResultHandler)。如果允許使用則設置為false。
protected boolean safeResultHandlerEnabled = true;
// 是否開啟自動駝峰命名規則(camel case)映射,即從經典數據庫列名 A_COLUMN
// 到經典 Java 屬性名 aColumn 的類似映射。默認false
protected boolean mapUnderscoreToCamelCase;
// 當開啟時,任何方法的調用都會加載該對象的所有屬性。否則,每個屬性會按需加載。默認值false (true in ≤3.4.1)
protected boolean aggressiveLazyLoading;
// 是否允許單一語句返回多結果集(需要兼容驅動)。
protected boolean multipleResultSetsEnabled = true;
// 允許 JDBC 支持自動生成主鍵,需要驅動兼容。這就是insert時獲取mysql自增主鍵/oracle sequence的開關。
// 注:一般來說,這是希望的結果,應該默認值為true比較合適。
protected boolean useGeneratedKeys;
// 使用列標簽代替列名,一般來說,這是希望的結果
protected boolean useColumnLabel = true;
// 是否啟用緩存
protected boolean cacheEnabled = true;
// 指定當結果集中值為 null 的時候是否調用映射對象的 setter(map 對象時為 put)方法,
// 這對于有 Map.keySet() 依賴或 null 值初始化的時候是有用的。
protected boolean callSettersOnNulls;
// 允許使用方法簽名中的名稱作為語句參數名稱。 為了使用該特性,你的工程必須采用Java 8編譯,
// 并且加上-parameters選項。(從3.4.1開始)
protected boolean useActualParamName = true;
//當返回行的所有列都是空時,MyBatis默認返回null。 當開啟這個設置時,MyBatis會返回一個空實例。
// 請注意,它也適用于嵌套的結果集 (i.e. collectioin and association)。(從3.4.2開始)
// 注:這里應該拆分為兩個參數比較合適, 一個用于結果集,一個用于單記錄。
// 通常來說,我們會希望結果集不是null,單記錄仍然是null
protected boolean returnInstanceForEmptyRow;
// 指定 MyBatis 增加到日志名稱的前綴。
protected String logPrefix;
// 指定 MyBatis 所用日志的具體實現,未指定時將自動查找。一般建議指定為slf4j或log4j
protected Class<? extends Log> logImpl;
// 指定VFS的實現, VFS是mybatis提供的用于訪問AS內資源的一個簡便接口
protected Class<? extends VFS> vfsImpl;
// MyBatis 利用本地緩存機制(Local Cache)防止循環引用(circular references)和加速重復嵌套查詢。
// 默認值為 SESSION,這種情況下會緩存一個會話中執行的所有查詢。
// 若設置值為 STATEMENT,本地會話僅用在語句執行上,對相同 SqlSession 的不同調用將不會共享數據。
protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
// 當沒有為參數提供特定的 JDBC 類型時,為空值指定 JDBC 類型。 某些驅動需要指定列的 JDBC 類型,
// 多數情況直接用一般類型即可,比如 NULL、VARCHAR 或 OTHER。
protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
// 指定對象的哪個方法觸發一次延遲加載。
protected Set<String> lazyLoadTriggerMethods = new HashSet<>(
Arrays.asList("equals", "clone", "hashCode", "toString"));
// 設置超時時間,它決定驅動等待數據庫響應的秒數。默認不超時
protected Integer defaultStatementTimeout;
// 為驅動的結果集設置默認獲取數量。
protected Integer defaultFetchSize;
// SIMPLE 就是普通的執行器;REUSE 執行器會重用預處理語句(prepared statements);
// BATCH 執行器將重用語句并執行批量更新。
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
// 指定 MyBatis 應如何自動映射列到字段或屬性。
// NONE 表示取消自動映射;
// PARTIAL 只會自動映射沒有定義嵌套結果集映射的結果集。
// FULL 會自動映射任意復雜的結果集(無論是否嵌套)。
protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
// 指定發現自動映射目標未知列(或者未知屬性類型)的行為。這個值應該設置為WARNING比較合適
protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
// settings下的properties屬性
protected Properties variables = new Properties();
// 默認的反射器工廠,用于操作屬性、構造器方便
protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
// 對象工廠, 所有的類resultMap類都需要依賴于對象工廠來實例化
protected ObjectFactory objectFactory = new DefaultObjectFactory();
// 對象包裝器工廠,主要用來在創建非原生對象,比如增加了某些監控或者特殊屬性的代理類
protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
// 延遲加載的全局開關。當開啟時,所有關聯對象都會延遲加載。特定關聯關系中可通過設置fetchType屬性來覆蓋該項的開關狀態。
protected boolean lazyLoadingEnabled = false;
// 指定 Mybatis 創建具有延遲加載能力的對象所用到的代理工具。MyBatis 3.3+使用JAVASSIST
protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL
// MyBatis 可以根據不同的數據庫廠商執行不同的語句,這種多廠商的支持是基于映射語句中的 databaseId 屬性。
protected String databaseId;
/**
* Configuration factory class. Used to create Configuration for loading
* deserialized unread properties.
*
* @see <a >Issue
* 300 (google code)</a>
*/
protected Class<?> configurationFactory;
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
// mybatis插件列表
protected final InterceptorChain interceptorChain = new InterceptorChain();
protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
// 類型注冊器, 用于在執行sql語句的出入參映射以及mybatis-config文件里的各種配置
// 比如<transactionManager type="JDBC"/><dataSource type="POOLED">時使用簡寫, 后面會詳細解釋
protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>(
"Mapped Statements collection")
.conflictMessageProducer((savedValue, targetValue) -> ". please check " + savedValue.getResource()
+ " and " + targetValue.getResource());
protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");
protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");
protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");
protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection");
protected final Set<String> loadedResources = new HashSet<>();
protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers");
protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>();
protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>();
protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>();
protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>();
/*
* A map holds cache-ref relationship. The key is the namespace that references
* a cache bound to another namespace and the value is the namespace which the
* actual cache is bound to.
*/
protected final Map<String, String> cacheRefMap = new HashMap<>();
public Configuration(Environment environment) {
this();
this.environment = environment;
}
public Configuration() {
//TypeAliasRegistry(類型別名注冊器)
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
typeAliasRegistry.registerAlias("LRU", LruCache.class);
typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
typeAliasRegistry.registerAlias("WEAK", WeakCache.class);
typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
languageRegistry.register(RawLanguageDriver.class);
}
-
SqlSessionFactory 接口
默認實現類是DefaultSQLSessionFactory類
SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
Configuration getConfiguration();
三、加載全局配置文件流程
-
入口:SqlSessionFactoryBuilder#build
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
// XMLConfigBuilder:用來解析XML配置文件
// 使用構建者模式
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// parser.parse():使用XPATH解析XML配置文件,將配置文件封裝為Configuration對象
// 返回DefaultSqlSessionFactory對象,該對象擁有Configuration對象(封裝配置文件信息)
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
流程分析圖
源碼閱讀
-
XMLConfigBuilder#構造參數
// XMLConfigBuilder:用來解析XML配置文件
// 使用構建者模式
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
具體實現
XmlConfigBuilder#構造函數
XMLConfigBuilder:用來解析XML配置文件(使用構建者模式)
public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
}
1. XpathParser#構造函數
用來使用XPath語法解析XML的解析器
public XPathParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) {
commonConstructor(validation, variables, entityResolver);
// 解析XML文檔為Document對象
this.document = createDocument(new InputSource(inputStream));
}
1.1 XPathParser#createDocument
解析全局配置文件,封裝為Document對象(封裝一些子節點,使用XPath語法解析獲取)
private Document createDocument(InputSource inputSource) {
// important: this must only be called AFTER common constructor
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 進行dtd或者Schema校驗
factory.setValidating(validation);
factory.setNamespaceAware(false);
// 設置忽略注釋為true
factory.setIgnoringComments(true);
// 設置是否忽略元素內容中的空白
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(entityResolver);
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
}
});
// 通過dom解析,獲取Document對象
return builder.parse(inputSource);
} catch (Exception e) {
throw new BuilderException("Error creating document instance. Cause: " + e, e);
}
}
2. XMLConfigBuilder#構造函數
創建Configuration對象,同時初始化內置類的別名
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
// 創建Configuration對象,并通過TypeAliasRegistry注冊一些Mybatis內部相關類的別名
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
2.1Configuration#構造函數
創建Configuration對象,同時初始化內置類的別名
public Configuration() {
//TypeAliasRegistry(類型別名注冊器)
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
typeAliasRegistry.registerAlias("LRU", LruCache.class);
typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
typeAliasRegistry.registerAlias("WEAK", WeakCache.class);
typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);
typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);
typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);
typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);
languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
languageRegistry.register(RawLanguageDriver.class);
}
-
XMLConfigBuilder#parse
//使用XPATH解析XML配置文件,將配置文件封裝為Configuration對象
parser.parse();
具體實現
XMLConfigBuilder#parse
解析XML配置文件
/**
* 解析XML配置文件
* @return
*/
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
// parser.evalNode("/configuration"):通過XPATH解析器,解析configuration根節點
// 從configuration根節點開始解析,最終將解析出的內容封裝到Configuration對象中
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
1. XPathParser#evalNode(xpath語法)
XPath解析器,專門用來通過Xpath語法解析XML返回XNode節點
public XNode evalNode(String expression) {
// 根據XPATH語法,獲取指定節點
return evalNode(document, expression);
}
public XNode evalNode(Object root, String expression) {
Node node = (Node) evaluate(expression, root, XPathConstants.NODE);
if (node == null) {
return null;
}
return new XNode(this, node, variables);
}
2. XMLConfigBuilder#parseConfiguration(XNode)
從configuration根節點開始解析,最終將解析出的內容封裝到Configuration對象中
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
// 解析</properties>標簽
propertiesElement(root.evalNode("properties"));
// 解析</settings>標簽
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
// 解析</typeAliases>標簽
typeAliasesElement(root.evalNode("typeAliases"));
// 解析</plugins>標簽
pluginElement(root.evalNode("plugins"));
// 解析</objectFactory>標簽
objectFactoryElement(root.evalNode("objectFactory"));
// 解析</objectWrapperFactory>標簽
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
// 解析</reflectorFactory>標簽
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
// 解析</environments>標簽
environmentsElement(root.evalNode("environments"));
// 解析</databaseIdProvider>標簽
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
// 解析</typeHandlers>標簽
typeHandlerElement(root.evalNode("typeHandlers"));
// 解析</mappers>標簽 加載映射文件流程主入口
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
-
SqlSessionFactoryBuilder#build
返回DefaultSqlSessionFactory對象,該對象擁有Configuration對象(封裝配置文件信息)
// 返回DefaultSqlSessionFactory對象,該對象擁有Configuration對象(封裝配置文件信息)
return build(parser.parse());
public SqlSessionFactory build(Configuration config) {
// 創建SqlSessionFactory接口的默認實現類
return new DefaultSqlSessionFactory(config);
}
總結
1. SqlSessionFactoryBuilder去創建SqlSessionFactory時,需傳入一個Configuration對象
2. XMLConfigBuilder會去實例化Configuration對象
3. XMLConfigBuilder會去初始化Configuration對象
- 通過XPathParser去解析全局配置文件,想成Document對象
- 通過XPathParser去獲取指定節點的XNode對象
- 解析Xnode對象的信息,然后封裝到Configuration對象中