第一節 從零開始手寫 mybatis(一)MVP 版本 中咱們實現了一個最基本的能夠運行的 mybatis。java
第二節 從零開始手寫 mybatis(二)mybatis interceptor 插件機制詳解git
第三節 從零開始手寫 mybatis(三)jdbc pool 從零實現數據庫鏈接池github
本節咱們一塊兒來學習一下 mybatis 中的事務管理。spring
mybatis 事務有兩種使用方式:sql
這個是對事務的一個工廠,接口以下:數據庫
public interface TransactionFactory { /** * Sets transaction factory custom properties. * @param props */ void setProperties(Properties props); /** * Creates a {@link Transaction} out of an existing connection. * @param conn Existing database connection * @return Transaction * @since 3.1.0 */ Transaction newTransaction(Connection conn); /** * Creates a {@link Transaction} out of a datasource. * @param dataSource DataSource to take the connection from * @param level Desired isolation level * @param autoCommit Desired autocommit * @return Transaction * @since 3.1.0 */ Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit); }
主要就是如何根據一個 DataSource 建立一個 Transaction。mybatis
實際上總體感受意義不大。框架
最核心的仍是要看一下 Transaction 的實現。ide
public interface Transaction { /** * Retrieve inner database connection * @return DataBase connection * @throws SQLException */ Connection getConnection() throws SQLException; /** * Commit inner database connection. * @throws SQLException */ void commit() throws SQLException; /** * Rollback inner database connection. * @throws SQLException */ void rollback() throws SQLException; /** * Close inner database connection. * @throws SQLException */ void close() throws SQLException; /** * Get transaction timeout if set * @throws SQLException */ Integer getTimeout() throws SQLException; }
這裏最核心的實際上只有 commit() 和 rollback(),其餘的都是能夠忽略的。學習
針對 getTimeout() 咱們就能夠爲 mybatis 提供一個操做的超時機制。
基於 jdbc 機制的一些處理。
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; } @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(); } } @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); } } } 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; } }
這裏總體的實現實際上很是簡單,就是主動設置了一下自動提交的屬性。
這個是另外一個實現,實際上更加簡單。
commit() 和 rollback() 實現都是空的。
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; } @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; } }
ManagedTransaction對事務的commit和rollback交給了容器去管理,本身自己並無作任何處理。
若是Mybatis是單獨運行的,沒有其餘框架管理,此時mybatis內部會對下段代碼實現。
con.setAutoCommit(false); //此處命令通知數據庫,今後刻開始從當前Connection通道推送而來的 //SQL語句屬於同一個業務中這些SQL語句在數據庫中應該保存到同一個 //Transaction中.這個Transaction的行爲(commit,rollback)由當前Connection管理. try{ //推送sql語句命令……..; con.commit();//通知Transaction提交. }catch(SQLException ex){ con.rollback();//通知Transaction回滾. }
總體來講這種寫法比較原始,咱們能夠將原本交給 connection 處理的事務,統一調整爲使用事務管理器處理。
固然針對 mybatis,大部分都是單個語句的執行。
用於使用 connection 時,實際上獲得的是 mybatis 事務管理器封裝以後的 connection。
實際上 spring 的整合,可能適用性更強一些。
看完了 mybatis 的實現原理以後,咱們的實現就變得很是簡單。
咱們能夠簡化上面的一些實現,保留核心的部分便可。
咱們只保留核心的 3 個接口。
/** * 事務管理 */ public interface Transaction { /** * Retrieve inner database connection * @return DataBase connection */ Connection getConnection(); /** * Commit inner database connection. */ void commit(); /** * Rollback inner database connection. */ void rollback(); }
這個實現,咱們的 commit 和 rollback 什麼都不作。
/** * 事務管理 * * @since 0.0.18 */ public class ManageTransaction implements Transaction { /** * 數據信息 * @since 0.0.18 */ private final DataSource dataSource; /** * 隔離級別 * @since 0.0.18 */ private final TransactionIsolationLevel isolationLevel; /** * 鏈接信息 * @since 0.0.18 */ private Connection connection; public ManageTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel) { this.dataSource = dataSource; this.isolationLevel = isolationLevel; } public ManageTransaction(DataSource dataSource) { this(dataSource, TransactionIsolationLevel.READ_COMMITTED); } @Override public Connection getConnection() { try { if(this.connection == null) { Connection connection = dataSource.getConnection(); connection.setTransactionIsolation(isolationLevel.getLevel()); this.connection = connection; } return connection; } catch (SQLException throwables) { throw new MybatisException(throwables); } } @Override public void commit() { //nothing } @Override public void rollback() { //nothing } }
這裏和上面的相比較,多出了 commit 和 rollback 的邏輯處理。
package com.github.houbb.mybatis.transaction.impl; import com.github.houbb.mybatis.constant.enums.TransactionIsolationLevel; import com.github.houbb.mybatis.exception.MybatisException; import com.github.houbb.mybatis.transaction.Transaction; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * 事務管理 * * @since 0.0.18 */ public class JdbcTransaction implements Transaction { /** * 數據信息 * @since 0.0.18 */ private final DataSource dataSource; /** * 隔離級別 * @since 0.0.18 */ private final TransactionIsolationLevel isolationLevel; /** * 自動提交 * @since 0.0.18 */ private final boolean autoCommit; /** * 鏈接信息 * @since 0.0.18 */ private Connection connection; public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel, boolean autoCommit) { this.dataSource = dataSource; this.isolationLevel = isolationLevel; this.autoCommit = autoCommit; } public JdbcTransaction(DataSource dataSource) { this(dataSource, TransactionIsolationLevel.READ_COMMITTED, true); } @Override public Connection getConnection(){ try { if(this.connection == null) { Connection connection = dataSource.getConnection(); connection.setTransactionIsolation(isolationLevel.getLevel()); connection.setAutoCommit(autoCommit); this.connection = connection; } return connection; } catch (SQLException throwables) { throw new MybatisException(throwables); } } @Override public void commit() { try { //非自動提交,才執行 commit 操做 if(connection != null && !this.autoCommit) { connection.commit(); } } catch (SQLException throwables) { throw new MybatisException(throwables); } } @Override public void rollback() { try { //非自動提交,才執行 commit 操做 if(connection != null && !this.autoCommit) { connection.rollback(); } } catch (SQLException throwables) { throw new MybatisException(throwables); } } }