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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With