鍍金池/ 問答/Java  數(shù)據(jù)庫/ 為什么JDBC事務(wù)里面要使用 rollback() ?

為什么JDBC事務(wù)里面要使用 rollback() ?

try {

        connection.setAutoCommit(false);


        bankDao.transferMoney(+2000, 1, connection); //帳號1 增加2000


        if(true){
            throw new RuntimeException(); //模擬報錯
        }

        bankDao.transferMoney(-2000, 2, connection);//帳號2 減少2000


        connection.commit();

    } catch (Exception e) {

        try {

            connection.rollback();
            System.out.println("回滾事務(wù)");

        } catch (Exception e1) {

            e1.printStackTrace();

        }

    }

我發(fā)現(xiàn)就算我沒有使用connection.rollback(), 由于事務(wù)還沒有提交, 數(shù)據(jù)庫里面的數(shù)據(jù)還是不會發(fā)生改變, 就是用或者是不用的效果也是一樣, 那我為什么還要使用connection.rollback()呢? 謝謝

回答
編輯回答
入她眼

你的本次兩個SQL語句包含在一個事物中。
在你的這個事物中包含了更新操作,而mysql的 innodb是一個行級鎖,按照mysql的默認事物級別:Repeated Read
如果你不及時提交或者回滾,那么造成的影響可能有如下兩種:

  1. 當另一個事物需要對這一行進行更新的時候是會被阻塞的。一直等到事物超時釋放。
  2. 你這個事物如果不及時提交或者回滾。那么其他事物在讀取的時候只會讀取到你開始事物之前的那一個版本的數(shù)據(jù)。

所以一個事物要么盡快提交,要么盡快回滾。

順便你可以去看下oracle關(guān)于事物的一個官方文檔:
https://docs.oracle.com/javas...

2018年8月12日 21:13
編輯回答
女流氓

你這個connection雖然還沒提交,但是也沒關(guān)閉,這樣其他人就沒法修改你正在改的那些行。

2017年5月26日 04:36
編輯回答
瘋子范

開啟事務(wù)后,一定要跟上 commit 或 rollback,及時釋放可能鎖住的數(shù)據(jù)。
你不用rollback()表面和用了rollback()效果一樣,但是不用rollback()可能導(dǎo)致被鎖住的數(shù)據(jù)不能及時的釋放(需要等事物超時釋放),會影響下一次的事物操作。

jdbc api 對rollback()方法的描述。

void rollback()
       throws SQLException
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.
Throws:
SQLException - if a database access error occurs, this method is called while participating in a distributed transaction, this method is called on a closed connection or this Connection object is in auto-commit mode
See Also:
setAutoCommit(boolean)
2017年5月10日 03:27