第一節 從零開始手寫 mybatis(一)MVP 版本 中我們實現了一個最基本的可以運行的 mybatis。
第二節 從零開始手寫 mybatis(二)mybatis interceptor 插件機制詳解
第三節 從零開始手寫 mybatis(三)jdbc pool 從零實現資料庫連接池
本節我們一起來學習一下 mybatis 中的事務管理。
mybatis 事務有兩種使用方式:
這個是對事務的一個工廠,接口如下:
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。
實際上整體感覺意義不大。
最核心的還是要看一下 Transaction 的實現。
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(&34; + connection + &34;); } connection.commit(); } } @Override public void rollback() throws SQLException { if (connection != null && !connection.getAutoCommit()) { if (log.isDebugEnabled()) { log.debug(&34; + connection + &34;); } connection.rollback(); } } @Override public void close() throws SQLException { if (connection != null) { resetAutoCommit(); if (log.isDebugEnabled()) { log.debug(&34; + connection + &34;); } connection.close(); } } protected void setDesiredAutoCommit(boolean desiredAutoCommit) { try { if (connection.getAutoCommit() != desiredAutoCommit) { if (log.isDebugEnabled()) { log.debug(&34; + desiredAutoCommit + &34; + connection + &34;); } connection.setAutoCommit(desiredAutoCommit); } } catch (SQLException e) { // Only a very poorly implemented driver would fail here, // and there&34;Error configuring AutoCommit. &34;Your driver may not support getAutoCommit() or setAutoCommit(). &34;Requested setting: &34;. Cause: &34;Resetting autocommit to true on JDBC Connection [&34;]&34;Error resetting autocommit to true &34;before closing the connection. Cause: &34;Opening JDBC Connection&34;Closing JDBC Connection [&34;]&34;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); } }}