MyBatis事務

數據很重要

 

在介紹MyBatis事務之前,先普及下數據庫事務相關知識

事務(Transaction)是訪問並可能更新數據庫中各種數據項的一個程序執行單元(unit)。事務通常由高級數據庫操縱語言或編程語言(如SQL,C++或Java)書寫的用戶程序的執行所引起,並用形如begin transactionend transaction語句(或函數調用)來界定。事務由事務開始(begin transaction)和事務結束(end transaction)之間執行的全體操作組成。一個事務可以是一條SQL語句,一組SQL語句或整個程序。

它有四大特性:原子性、一致性、隔離性、持續性,簡稱ACID

1.原子性:事務是應用中最小的執行單位,就如原子是自然界最小顆粒,具有不可再分的特徵一樣。事務是應用中不可再分的最小邏輯執行體,一組事務,要麼成功;要麼撤回。

2.一致性:事務執行的結果,必須使數據庫從一個一致性狀態,變到另一個一致性狀態。當數據庫中只包含事務成功提交的結果時,數據庫處於一致性狀態。一致性是通過原子性來保證的。有非法數據(外鍵約束之類),事務撤回。

3.隔離性:各個事務的執行互不干擾,任意一個事務的內部操作對其他併發的事務,都是隔離的。也就是說:併發執行的事務之間不能看到對方的中間狀態,併發執行的事務之間不能相互影響。事務獨立運行。一個事務處理後的結果,影響了其他事務,那麼其他事務會撤回。事務的100%隔離,需要犧牲速度。

4.持續性:持續性也稱爲持久性,指事務一旦提交,對數據所做的任何改變,都要記錄到永久存儲器中,通常是保存進物理數據庫。軟、硬件崩潰後,InnoDB數據表驅動會利用日誌文件重構修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit 選項 決定什麼時候吧事務保存到日誌裏。

讀取數據的三個概念:

1.髒讀(Dirty Reads):所謂髒讀就是對髒數據的讀取,而髒數據所指的就是未提交的數據。一個事務正在對一條記錄做修改,在這個事務完成並提交之前,這條數據是處於待定狀態的(可能提交也可能回滾),這時,第二個事務來讀取這條沒有提交的數據,並據此做進一步的處理,就會產生未提交的數據依賴關係。這種現象被稱爲髒讀。

2.不可重複讀(Non-Repeatable Reads):一個事務先後讀取同一條記錄,但兩次讀取的數據不同,我們稱之爲不可重複讀。也就是說,這個事務在兩次讀取之間該數據被其它事務所修改。

3.幻讀(Phantom Reads):一個事務按相同的查詢條件重新讀取以前檢索過的數據,卻發現其他事務插入了滿足其查詢條件的新數據,這種現象就稱爲幻讀。

事務的隔離級別:

1、Read Uncommitted(未授權讀取、讀未提交):這是最低的隔離等級,允許其他事務看到沒有提交的數據。這種等級會導致髒讀。如果一個事務已經開始寫數據,則另外一個事務則不允許同時進行寫操作,但允許其他事務讀此行數據。該隔離級別可以通過“排他寫鎖”實現。避免了更新丟失,卻可能出現髒讀。也就是說事務B讀取到了事務A未提交的數據。SELECT語句以非鎖定方式被執行,所以有可能讀到髒數據,隔離級別最低。

2.Read Committed(授權讀取、讀提交):讀取數據的事務允許其他事務繼續訪問該行數據,但是未提交的寫事務將會禁止其他事務訪問該行。該隔離級別避免了髒讀,但是卻可能出現不可重複讀。事務A事先讀取了數據,事務B緊接了更新了數據,並提交了事務,而事務A再次讀取該數據時,數據已經發生了改變。

3.repeatable read(可重複讀取):就是在開始讀取數據(事務開啓)時,不再允許修改操作,事務開啓,不允許其他事務的UPDATE修改操作,不可重複讀對應的是修改,即UPDATE操作。但是可能還會有幻讀問題。因爲幻讀問題對應的是插入INSERT操作,而不是UPDATE操作。避免了不可重複讀取和髒讀,但是有時可能出現幻讀。這可以通過“共享讀鎖”和“排他寫鎖”實現。

4.串行化、序列化:提供嚴格的事務隔離。它要求事務序列化執行,事務只能一個接着一個地執行,但不能併發執行。如果僅僅通過“行級鎖”是無法實現事務序列化的,必須通過其他機制保證新插入的數據不會被剛執行查詢操作的事務訪問到。序列化是最高的事務隔離級別,同時代價也花費最高,性能很低,一般很少使用,在該級別下,事務順序執行,不僅可以避免髒讀、不可重複讀,還避免了幻像讀。

原生JDBC給了事務定義的級別,在java.sql.Connection.java文件中:

public interface Connection  extends Wrapper, AutoCloseable {
    /**
     * 表示不支持事務的常量。
     */
    int TRANSACTION_NONE             = 0;
   /**
     * 可讀到未提交
     */
    int TRANSACTION_READ_UNCOMMITTED = 1;
    /**
     * 只能讀已提交
     */
    int TRANSACTION_READ_COMMITTED   = 2;
   /**
     * 可重複讀
     */
    int TRANSACTION_REPEATABLE_READ  = 4;
   /**
     * 串行化操作
     */
    int TRANSACTION_SERIALIZABLE     = 8;
   /**
     * 設置事務
     */
    void setTransactionIsolation(int level) throws SQLException;
}

具體實現:

 /**
     * @param level
     * @throws SQLException
     */
    public void setTransactionIsolation(int level) throws SQLException {
        synchronized (getConnectionMutex()) {
            checkClosed();

            if (this.hasIsolationLevels) {
                String sql = null;

                boolean shouldSendSet = false;

                if (getAlwaysSendSetIsolation()) {
                    shouldSendSet = true;
                } else {
                    if (level != this.isolationLevel) {
                        shouldSendSet = true;
                    }
                }

                if (getUseLocalSessionState()) {
                    shouldSendSet = this.isolationLevel != level;
                }

                if (shouldSendSet) {
                    switch (level) {
                        case java.sql.Connection.TRANSACTION_NONE:
                            throw SQLError.createSQLException("Transaction isolation level NONE not supported by MySQL", getExceptionInterceptor());

                        case java.sql.Connection.TRANSACTION_READ_COMMITTED:
                            sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";

                            break;

                        case java.sql.Connection.TRANSACTION_READ_UNCOMMITTED:
                            sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";

                            break;

                        case java.sql.Connection.TRANSACTION_REPEATABLE_READ:
                            sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";

                            break;

                        case java.sql.Connection.TRANSACTION_SERIALIZABLE:
                            sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";

                            break;

                        default:
                            throw SQLError.createSQLException("Unsupported transaction isolation level '" + level + "'", SQLError.SQL_STATE_DRIVER_NOT_CAPABLE,
                                    getExceptionInterceptor());
                    }

                    execSQL(null, sql, -1, null, DEFAULT_RESULT_SET_TYPE, DEFAULT_RESULT_SET_CONCURRENCY, false, this.database, null, false);

                    this.isolationLevel = level;
                }
            } else {
                throw SQLError.createSQLException("Transaction Isolation Levels are not supported on MySQL versions older than 3.23.36.",
                        SQLError.SQL_STATE_DRIVER_NOT_CAPABLE, getExceptionInterceptor());
            }
        }
    }

普及了數據庫和jdbc的事務級別後,然後再說MyBatis事務

MyBatis作爲Java語言的數據庫框架,對數據庫的事務管理是其非常重要的一個方面。本文將從事務的分類、配置和實現分析MyBatis的事務管理的實現機制。部分組件圖

MyBatis事務分類

事務接口定義在org.apache.ibatis.transaction.Transaction。核心方法:

public interface Transaction {

  /**
   * Retrieve inner database connection.
   * @return DataBase connection
   * @throws SQLException
   *           the SQL exception
   */
  Connection getConnection() throws SQLException;

  /**
   * Commit inner database connection.
   * @throws SQLException
   *           the SQL exception
   */
  void commit() throws SQLException;

  /**
   * Rollback inner database connection.
   * @throws SQLException
   *           the SQL exception
   */
  void rollback() throws SQLException;

  /**
   * Close inner database connection.
   * @throws SQLException
   *           the SQL exception
   */
  void close() throws SQLException;
}

它有兩種實現方式:

1、使用JDBC的事務管理機制:利用java.sql.Connection對象完成對事務的提交(commit())、回滾(rollback())、關閉(close())等

2、使用MANAGED的事務管理機制:這種機制MyBatis自身不會去實現事務管理,而是讓程序的容器如(tomcat,JBOSS,Weblogic,spring)來實現對事務的管理,此文暫不考慮

可在mybatis配置文件中配置其中一種事務處理方式:

 

Mybatis事務創建 

MyBatis事務的創建是交給TransactionFactory 事務工廠來創建的,如果我們將<transactionManager>的type 配置爲"JDBC",那麼,在MyBatis初始化解析<environment>節點時,會根據type="JDBC"創建一個JdbcTransactionFactory工廠,核心代碼:

/**
     * 解析<transactionManager>節點,創建對應的TransactionFactory
     * @param context
     * @return
     * @throws Exception
     */
  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      /*
            在Configuration初始化的時候,會通過以下語句,給JDBC和MANAGED對應的工廠類
            typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
            typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
            下述的resolveClass(type).newInstance()會創建對應的工廠實例
       */
      TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

dom樹解析就不說了,以前開發不經常來回解析xml嗎,xml文檔與java類之間的互轉,數據交換的一種,可以把xml當成一種組裝數據的方式,可以多層嵌套,現在流行後臺java註解解析和前臺json了。

如果type = "JDBC",則MyBatis會創建一個JdbcTransactionFactory.class 實例;如果type="MANAGED",則MyBatis會創建一個MangedTransactionFactory.class實例。
MyBatis對<transactionManager>節點的解析會生成 TransactionFactory實例;而對<dataSource>解析會生成datasouce實例。作爲<environment>節點,會根據TransactionFactory和DataSource實例創建一個Environment對象,代碼如下所示:

 private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      if (environment == null) {
        environment = context.getStringAttribute("default");
      }
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        //是和默認的環境相同時,解析之
        if (isSpecifiedEnvironment(id)) {
          //1.解析<transactionManager>節點,決定創建什麼類型的TransactionFactory
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          //2. 創建dataSource
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          //3. 使用了Environment內置的構造器Builder,傳遞id 事務工廠TransactionFactory和數據源DataSource
          Environment.Builder environmentBuilder = new Environment.Builder(id)
              .transactionFactory(txFactory)
              .dataSource(dataSource);
          configuration.setEnvironment(environmentBuilder.build());
        }
      }
    }
  }

Environment表示着一個數據庫的連接,生成後的Environment對象會被設置到Configuration實例中。

通過事務工廠TransactionFactory很容易獲取到Transaction對象實例。我們以JdbcTransaction爲例,看一下JdbcTransactionFactory是怎樣生成JdbcTransaction的,代碼如下:

public class JdbcTransactionFactory implements TransactionFactory {
 
  public void setProperties(Properties props) {
  }
 
    /**
     * 根據給定的數據庫連接Connection創建Transaction
     * @param conn Existing database connection
     * @return
     */
  public Transaction newTransaction(Connection conn) {
    return new JdbcTransaction(conn);
  }
 
    /**
     * 根據DataSource、隔離級別和是否自動提交創建Transacion
     *
     * @param ds
     * @param level Desired isolation level
     * @param autoCommit Desired autocommit
     * @return
     */
  public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
    return new JdbcTransaction(ds, level, autoCommit);
  }
}

JdbcTransactionFactory會創建JDBC類型的Transaction,即JdbcTransaction,ManagedTransactionFactory也會創建ManagedTransaction。下面分別深入JdbcTranaction 和ManagedTransaction,看它們到底是怎樣實現事務管理的。

 JdbcTransaction事務

 JdbcTransaction使用JDBC的提交和回滾事務管理機制 ,它依賴與從dataSource中取得的連接connection 來管理transaction 的作用域,connection對象的獲取被延遲到調用getConnection()方法。如果autocommit設置爲on,開啓狀態的話,它會忽略commit和rollback。

    直觀地講,就是JdbcTransaction是使用的java.sql.Connection 上的commit和rollback功能,JdbcTransaction只是相當於對java.sql.Connection事務處理進行了一次包裝(wrapper),Transaction的事務管理都是通過java.sql.Connection實現的。JdbcTransaction的代碼實現如下:

/**
 * @see JdbcTransactionFactory
 */
/**
 * @author Clinton Begin
 */
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;
  }
  
    /**
     * commit()功能 使用connection的commit()
     * @throws SQLException
     */
  public void commit() throws SQLException {
    if (connection != null && !connection.getAutoCommit()) {
      if (log.isDebugEnabled()) {
        log.debug("Committing JDBC Connection [" + connection + "]");
      }
      connection.commit();
    }
  }
  
    /**
     * rollback()功能 使用connection的rollback()
     * @throws SQLException
     */
  public void rollback() throws SQLException {
    if (connection != null && !connection.getAutoCommit()) {
      if (log.isDebugEnabled()) {
        log.debug("Rolling back JDBC Connection [" + connection + "]");
      }
      connection.rollback();
    }
  }
  
    /**
     * close()功能 使用connection的close()
     * @throws SQLException
     */
  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);
  }
}

 事務隔離級別(TransactionIsolationLevel )

mybatis定義了五種事務級別,在包org.apache.ibatis.session下,源代碼如下:

/**
 * @author Clinton Begin
 */
public enum TransactionIsolationLevel {
  NONE(Connection.TRANSACTION_NONE),
  READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
  READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),
  REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
  SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE);

  private final int level;

  TransactionIsolationLevel(int level) {
    this.level = level;
  }

  public int getLevel() {
    return level;
  }
}

和上面介紹的隔離級別對應

 

測試核心代碼:

            String resource = "conf/mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
					.build(inputStream);
			
			SqlSession sqlSession = sqlSessionFactory.openSession();
			userDao = new MybatisDaoImpl(sqlSession);
			User user =  userDao.selectUserById(1);
			
			sqlSession.commit();
			sqlSession.close();

 

總結:事務,先搞懂數據庫事務,然後看原生JDBC的事務表現,最後纔是框架包裝的事務。

 

參考網址:

0 . 這一次,帶你搞清楚MySQL的事務隔離級別!http://blog.itpub.net/31559358/viewspace-2221931/

1.  十分鐘搞懂MySQL四種事務隔離級別 https://juejin.im/post/5c9756296fb9a070ad504a05

 

2. JDBC 4.2 Specification規範 https://download.oracle.com/otn-pub/jcp/jdbc-4_2-mrel2-eval-spec/jdbc4.2-fr-spec.pdf?AuthParam=1588653978_d9c7458a368a7a1630e262c8325ca34b

也可在我的github上獲取:https://github.com/dongguangming/java/blob/master/jdbc4.2-fr-spec.pdf

 

3. 事務基礎和分佈式事務

https://www.ibm.com/developerworks/cn/cloud/library/cl-manage-cloud-transactions_1/index.html

4. mybatis jdbc transaction.java https://mybatis.org/mybatis-3/zh/jacoco/org.apache.ibatis.transaction.jdbc/JdbcTransaction.java.html 

5. The ABCs of JDBC, Part 5 - Transactions 

https://dzone.com/articles/jdbc-faq-transactions

6. Java JDBC Transaction Management and Savepoint

https://www.journaldev.com/2483/java-jdbc-transaction-management-savepoint

7. JDBC transaction performance tips

https://www.javaperformancetuning.com/tips/jdbctransaction.shtml

8. spring4-and-mybatis-transaction-example(要翻牆) https://edwin.baculsoft.com/2015/01/a-simple-spring-4-and-mybatis-transaction-example/

 

參考書籍:

MyBatis技術內幕

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章