Why is rollback () used in JDBC transactions?

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("");

        } catch (Exception e1) {

            e1.printStackTrace();

        }

    }

I find that even if I don"t use connection.rollback () , the data in the database will not change because the transaction has not been committed, even if I use it or not, so why should I use connection.rollback () ? Thank you

Apr.07,2021

your connection has not been submitted yet, but it has not been closed, so that no one else can modify the lines you are changing.


after opening a transaction, be sure to keep up with commit or rollback, to release data that may be locked in time.
the effect of using rollback () surface is the same as using rollback (), but not using rollback () may cause locked data not to be released in time (need to wait for things to be released in time), which will affect the next transaction operation.

jdbc api's description of the rollback () method.

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)

your two SQL statements are contained in one thing.
contains update operations in your transaction, and mysql's innodb is a row-level lock, according to mysql's default transaction level: Repeated Read .
if you do not submit or roll back in time, the impact may be as follows:

  1. it is blocked when another thing needs to make a update on this line. Wait until things are released on time.
  2. if your business is not submitted or rolled back in time. Then other things will only read the version of the data before you start the thing.

so a thing can either be submitted or rolled back as soon as possible.

by the way, you can take a look at one of oracle's official documents about things:
https://docs.oracle.com/javas.

.
Menu