# Mybatis之事務管理
### 簡介
Mybatis的事務管理分為兩種JdbcTransaction,ManagedTransaction。其中JdbcTransaction僅僅是對數據庫連接Connection的一個包裝、內部管理數據庫事務還是調用Connection的提交、回滾等事務操作方法。ManagedTransaction更直接、什么也沒有做。直接將事務交給外部容器管理。
### Mybatis事務管理相關類結構圖
類概覽:

類UML圖(典型的簡單工廠模式來創建Transaction):

- Transaction 封裝事務管理方法的接口
- TransactionFactory 抽象事務工廠生產方法
- JdbcTransactionFactory實現TransactionFactory、用于生產JdbcTransaction的工廠類
- ManagedTransactionFactory實現TransactionFactory、用于生產ManagedTransaction的工廠類
- JdbcTransaction實現Transaction、只是對事務進行了一層包裝、實際調用數據庫連接Connection的事務管理方法
- ManagedTransaction 實現Transaction沒有對數據庫連接做任何事務處理、交由外部容器管理
### 源碼事務
### 事務配置
Mybatis中關于事務的配置是通過`<transaction type="xx"/>`來指定的。配置如下:
~~~
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
~~~
- type為”JDBC”時、使用JdbcTransaction管理事務。
-
type為”managed”時、使用ManagedTransaction管理事務(也就是交由外部容器管理)
[Mybatis深入之初始化過程 ](http://blog.csdn.net/crave_shy/article/details/46013493 "Mybatis深入之初始化過程")中知道配置文件如何解析的、其中關于事務方面的解析:
~~~
private void environmentsElement(XNode context) throws Exception {
//只關注事務部分...
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
...
}
~~~
~~~
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type");
Properties props = context.getChildrenAsProperties();
TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a TransactionFactory.");
}
~~~
~~~
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
~~~
- 重點在于根據type類型判斷實例化何種TransactionFactory
- 前面已經知道Mybatis兩種事務配置的方式、這里使用的jdbc類型的事務
- 上一篇分析DataSource實例化過程中有一段是關于根據DataSource的type來獲取何種Factory的、這里原理同樣
- 通過TypeAliasRegistry根據type=’JDBC’來獲取TransactionFactory實現類JdbcTransactionFactory
關鍵在于JdbcTransactionFactory通過newInstance()使用無參構造函數時做了什么工作
~~~
public class JdbcTransactionFactory implements TransactionFactory {
public void setProperties(Properties props) {
}
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
}
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
return new JdbcTransaction(ds, level, autoCommit);
}
}
~~~
- JdbcTransactionFactory默認無參構造方法被調用
- setProperties沒有做任何實質性處理
- 對比ManagedTransactionFactory不再貼代碼
下面就是獲取具有事務特性的數據庫連接了
JdbcTransaction:
~~~
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
}
~~~
ManagedTransaction:
~~~
public Transaction newTransaction(Connection conn) {
return new ManagedTransaction(conn, closeConnection);
}
~~~
- 兩者都是通過Connection來創建具體的實例
JdbcTransaction:
~~~
public class JdbcTransaction implements Transaction {
private static final Log log = LogFactory.getLog(JdbcTransaction.class);
protected Connection connection;
protected DataSource dataSource;
protected TransactionIsolationLevel level;
protected boolean autoCommmit;
public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
dataSource = ds;
level = desiredLevel;
autoCommmit = desiredAutoCommit;
}
public JdbcTransaction(Connection connection) {
this.connection = connection;
}
public Connection getConnection() throws SQLException {
if (connection == null) {
openConnection();
}
return connection;
}
public void commit() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Committing JDBC Connection [" + connection + "]");
}
connection.commit();
}
}
public void rollback() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Rolling back JDBC Connection [" + connection + "]");
}
connection.rollback();
}
}
public void close() throws SQLException {
if (connection != null) {
resetAutoCommit();
if (log.isDebugEnabled()) {
log.debug("Closing JDBC Connection [" + connection + "]");
}
connection.close();
}
}
protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
try {
if (connection.getAutoCommit() != desiredAutoCommit) {
if (log.isDebugEnabled()) {
log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]");
}
connection.setAutoCommit(desiredAutoCommit);
}
} catch (SQLException e) {
// Only a very poorly implemented driver would fail here,
// and there's not much we can do about that.
throw new TransactionException("Error configuring AutoCommit. "
+ "Your driver may not support getAutoCommit() or setAutoCommit(). "
+ "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e);
}
}
protected void resetAutoCommit() {
try {
if (!connection.getAutoCommit()) {
// MyBatis does not call commit/rollback on a connection if just selects were performed.
// Some databases start transactions with select statements
// and they mandate a commit/rollback before closing the connection.
// A workaround is setting the autocommit to true before closing the connection.
// Sybase throws an exception here.
if (log.isDebugEnabled()) {
log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
log.debug("Error resetting autocommit to true "
+ "before closing the connection. Cause: " + e);
}
}
protected void openConnection() throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Opening JDBC Connection");
}
connection = dataSource.getConnection();
if (level != null) {
connection.setTransactionIsolation(level.getLevel());
}
setDesiredAutoCommit(autoCommmit);
}
}
~~~
- 從源碼中可知、JdbcTransaction如何管理事務的、如前面所說調用DataSource事務操作方法。
- 并且對select不進行事務控制
- 當使用DataSource創建數據庫連接時、數據庫的事務隔離級別使用DataSource默認的事務隔離級別
- 如需指定事務的隔離級別、必須手動創建JdbcTransaction(調用另一個構造函數)
- 關于事務隔離級別會在補充中有
ManagedTransaction:
~~~
public class ManagedTransaction implements Transaction {
private static final Log log = LogFactory.getLog(ManagedTransaction.class);
private DataSource dataSource;
private TransactionIsolationLevel level;
private Connection connection;
private boolean closeConnection;
public ManagedTransaction(Connection connection, boolean closeConnection) {
this.connection = connection;
this.closeConnection = closeConnection;
}
public ManagedTransaction(DataSource ds, TransactionIsolationLevel level, boolean closeConnection) {
this.dataSource = ds;
this.level = level;
this.closeConnection = closeConnection;
}
public Connection getConnection() throws SQLException {
if (this.connection == null) {
openConnection();
}
return this.connection;
}
public void commit() throws SQLException {
// Does nothing
}
public void rollback() throws SQLException {
// Does nothing
}
public void close() throws SQLException {
if (this.closeConnection && this.connection != null) {
if (log.isDebugEnabled()) {
log.debug("Closing JDBC Connection [" + this.connection + "]");
}
this.connection.close();
}
}
protected void openConnection() throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Opening JDBC Connection");
}
this.connection = this.dataSource.getConnection();
if (this.level != null) {
this.connection.setTransactionIsolation(this.level.getLevel());
}
}
}
~~~
- 重點看一下`commit()``rollback()`方法,沒有方法體。驗證前面其關于事務的管理方式
到這里事務暫時告一段落、一般在使用時會與spring結合、將數據庫連接、事務管理都交由spring管理。
### 補充
數據庫隔離級別:
先對不同隔離級別涉及到的名詞解釋:
? 臟讀: 對于兩個事物 T1, T2, T1 讀取了已經被 T2 更新但還沒有被提交的字段. 之后, 若 T2 回滾, T1讀取的內容就是臨時且無效的.
? 不可重復讀: 對于兩個事物 T1, T2, T1 讀取了一個字段, 然后 T2 更新了該字段. 之后, T1再次讀取同一個字段, 值就不同了.
? 幻讀: 對于兩個事物 T1, T2, T1 從一個表中讀取了一個字段, 然后 T2 在該表中插入了一些新的行. 之后, 如果 T1 再次讀取同一個表, 就會多出幾
具體的隔離級別定義:
READ UNCOMMITTED(讀未提交數據) 允許事務讀取未被其他事務提交的變更,臟讀、不可重復讀和幻讀的問題都會出現
READ COMMITED(讀已提交數據) 只允許事務讀取已經被其他事務提交的變更,可以避免臟讀,但不可重復讀和幻讀問題仍然會出現
REPEATABLE READ(可重復讀) 確保事務可以多次從一個字段中讀取相同的值,在這個事務持續期間,禁止其他事務對這個字段進行更新,可以避免臟讀和不可重復讀,但幻讀的問題依然存在
SERIALIZABLE(串行化) 確保事務可以從一個表中讀取相同的行,在這個事務持續期間,禁止其他事務對該表執行插入、更新和刪除操作,所有并發問題都可以避免,但性能十分低
Oracle 支持的 2 種事務隔離級別:READ COMMITED, SERIALIZABLE. Oracle 默認的事務隔離級別為: READ COMMITED
Mysql 支持 4 中事務隔離級別. Mysql 默認的事務隔離級別為: REPEATABLE READ
更多內容:[Mybatis 目錄](http://blog.csdn.net/crave_shy/article/details/45825599)