Sobes.tech
Junior — Middle

How is control over transaction completion and rollback when necessary carried out?

sobes.tech AI

Answer from AI

In Java, transaction control and rollback are usually managed using transaction management APIs, such as JDBC or frameworks like Spring.

Main approach:

  • A transaction begins (for example, connection.setAutoCommit(false) in JDBC).
  • Necessary database operations are performed.
  • If all operations succeed, commit() is called to save the changes.
  • If an exception or error occurs, rollback() is called to undo all changes made within the transaction.

Example using JDBC:

Connection connection = null;
try {
    connection = dataSource.getConnection();
    connection.setAutoCommit(false); // start transaction

    // Perform database operations

    connection.commit(); // commit transaction
} catch (SQLException e) {
    if (connection != null) {
        try {
            connection.rollback(); // rollback on error
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    e.printStackTrace();
} finally {
    if (connection != null) {
        try {
            connection.setAutoCommit(true);
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

In Spring Framework, you can use the @Transactional annotation, which automatically manages transactions, calling commit or rollback depending on the success of the method execution.

How is control over transaction completion and… - sobes.tech