Reputation: 61
If I don't use connection.rollback()
, due to the transaction is not yet commit, I can see the database's data also will not change anything, then why do I still need to use connection.rollback()
?
try {
connection.setAutoCommit(false);
bankDao.transferMoney(+2000, 1, connection); //account1:+$2000
if(true){
throw new RuntimeException(); //make error
}
bankDao.transferMoney(-2000, 2, connection);//account2:-$2000
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
System.out.println("something wrong, roll back");
} catch (Exception e1) {
e1.printStackTrace();
}
}
Upvotes: 6
Views: 2515
Reputation: 18408
You have a client-side process (your program) and a server-side process (the DBMS components that are listening/waiting for your commands).
If you just let the client-side process die (that is, let a runtime exception propagate all the way up without some catch() or finally{} ever stepping in to do the connection.close() or similar) then the server-side process will still be waiting for commands from a client-side process that no longer exists. It will be holding on to any locks it has acquired and that will change only when the server-side process finally times out.
So better to do all the wrapping-up properly when your client-side process is still alive.
Upvotes: 1
Reputation: 108992
You need to explicitly rollback to make sure the transactions ends. If you don't explicitly commit or rollback, then - if the connection continues to be used - the changes may be committed later by accident by other parts of your application. Explicitly rolling back prevents that.
In other cases, the connection close will end the transaction. However it is driver-specific whether a connection close will commit or rollback the transaction. The Connectionc.close()
documentation says:
It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the
close
method is called and there is an active transaction, the results are implementation-defined.
Not explicitly rolling back your transaction may also lead to the transaction living longer than necessary, holding locks etc that may prevent other transactions from completing their work.
Upvotes: 5
Reputation: 1916
You are right that the data is not committed when exception occurred and the transaction will eventually be rollbacked by the database.
Internally InnoDB has implicitly rollbak on error, InnoDB error handling, but unless you really understand all the scenarios, an explicitly call to connection.rollback() can make sure that the transaction is ended(rollbacked) as early as possible. Note that a transaction ends when you call commit or rollback.
In the example code, what if the exception is on lines other than commit() , such as bankDao.transferMoney due to some reason?
You need the rollabck to end the transaction.
Upvotes: 2