Mybatis|事務管理

1. 什麼是事務
事務是指的是一個業務上的最小不可再分單元,通常一個事務對應了一個完整的業務,而一個完整的業務需要批量的DML語句共同聯合完成。一般,同一個事務中的SQL語句是儲存到資料庫中的同一個Transaction物件中,原因是Transaction具有一致性的特徵,也就是說事務中如果有任何一條sql語句執行失敗,那麼這個事務中所有的SQL語句都會被判定為無效SQL。
2. MyBatis事務管理策略
2.1 親自實現JDBC管理方式
如果Mybatis是單獨執行的,沒有其他框架管理,此時mybatis內部會對下段程式碼實現。
con.setAutoCommit(false); //此處命令通知資料庫,從此刻開始從當前Connection通道推送而來的 //SQL語句屬於同一個業務中這些SQL語句在資料庫中應該儲存到同一個 //Transaction中.這個Transaction的行為(commit,rollback)由當前Connection 管理. try{ //推送sql語句命令……..; con.commit();//通知Transaction提交. }catch(SQLException ex){ con.rollback();//通知Transaction回滾. }
2.2 委託實現JDBC管理方式
如果實現Spring+MyBatis,可以將對Transasaction 管理交給Spring框架來管理實現。
開發人員可以在mybatis-configuration.xml 檔案中配置,採用指定的管理方式。

當<transactionManager type="JDBC"/>時,就會呼叫JdbcTransaction。
當<transactionManager type="MANAGED"/>時,呼叫ManagedTransaction。
3. MyBatis中Transaction介面
mybatis 支援的兩種事務型別管理器,Transactions介面中對兩種事務管理方式,進行行為約束。有四種方法對事物管理,具體介紹看下面程式碼。
public interface Transaction { //JDBC中事務手動管理,需要依靠connection物件,getConnection方法約束取得Connection物件方式。 //一般來說,要麼是手動new一個Connection,要麼就是從資料庫連池獲得。 Connection getConnection() throws SQLException; //設定在什麼情況下執行commit()命令 void commit() throws SQLException; //設定在什麼情況下執行rollback()命令 void rollback() throws SQLException; //業務完畢後,處理Connection物件。 //一般有兩種形式,將這個Connection物件銷燬,將Connection返回資料庫連線池中。 void close() throws SQLException; //Connection向資料庫索要一個Transaction物件時的最大等待時間。 Integer getTimeout() throws SQLException; }
4. Transaction的介面實現類
Transaction介面中有連個實現類。
4.1 JdbcTransaction
JdbcTransaction直接使用JDBC的提交和回滾事務管理機制 。它依賴與從dataSource中取得的連線connection 來管理transaction 的作用域,connection物件的獲取被延遲到呼叫getConnection()方法。如果autocommit設定為on,開啟狀態的話,它會忽略commit和rollback。
public class JdbcTransaction implements Transaction { private static final Log log = LogFactory.getLog(JdbcTransaction.class); protected Connection connection; protected DataSource dataSource; protected TransactionIsolationLevel level; // MEMO: We are aware of the typo. See #941 protected boolean autoCommmit; //資料來源、隔離級別、是否自動提交 public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) { dataSource = ds; level = desiredLevel; autoCommmit = desiredAutoCommit; } //根據當前的資料庫連線connection建立transaction public JdbcTransaction(Connection connection) { this.connection = connection; } //返回一個Connection物件,其中openConnection方法是得到Connection 具體實現。 @Override public Connection getConnection() throws SQLException { if (connection == null) { openConnection(); } return connection; } @Override public void commit() throws SQLException { if (connection != null && !connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug("Committing JDBC Connection [" + connection + "]"); } connection.commit(); } } @Override public void rollback() throws SQLException { if (connection != null && !connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug("Rolling back JDBC Connection [" + connection + "]"); } connection.rollback(); } } //close方法中我們可以看到connection被回收到資料庫連線池前,執行了一個resetAutoCommit()。 @Override 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) { if (log.isDebugEnabled()) { log.debug("Error resetting autocommit to true " + "before closing the connection.Cause: " + e); } } } /** * openConnection方法中做了三件事情: * 1. 資料庫連線池得到了一個Connection * 2. 設定資料庫的事務隔離級別 * 3.呼叫了con.setAutoCommit(false),再setDesireAutoCommit(autoCommit)。 **/ 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); } @Override public Integer getTimeout() throws SQLException { return null; } }
4.2 ManagedTransaction
我們可以在這個類中看到它的commit方法和rollback方法沒有具體實現。
ManagedTransaction是讓容器來管理事務Transaction的整個生命週期,使用ManagedTransaction的commit和rowblkrollback功能不會對事務有任何影響,它沒有具體實現,它將事務管理權交給容器來實現。
public class ManagedTransaction implements Transaction { private static final Log log = LogFactory.getLog(ManagedTransaction.class); private DataSource dataSource; private TransactionIsolationLevel level; private Connection connection; private final 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; } @Override public Connection getConnection() throws SQLException { if (this.connection == null) { openConnection(); } return this.connection; } @Override public void commit() throws SQLException { // Does nothing } @Override public void rollback() throws SQLException { // Does nothing } @Override 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()); } } @Override public Integer getTimeout() throws SQLException { return null; } }