Sobes.tech
Middle

How to manage transactions in Java code? How is it done through JDBC?

sobes.tech AI

Answer from AI

In Java, transaction management can be done programmatically or declaratively (for example, using Spring). With JDBC, transactions are managed manually:

  • Disable autocommit: connection.setAutoCommit(false);
  • Perform the necessary SQL operations
  • If everything goes well, call connection.commit();
  • If an error occurs, call connection.rollback();
  • At the end, you can restore autocommit to its original state if needed

Example:

Connection connection = null;
try {
    connection = dataSource.getConnection();
    connection.setAutoCommit(false); // disable autocommit

    // Execute SQL operations
    PreparedStatement stmt = connection.prepareStatement("INSERT INTO users(name) VALUES (?)");
    stmt.setString(1, "John");
    stmt.executeUpdate();

    // Other operations

    connection.commit(); // commit the 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); // restore autocommit
            connection.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

This approach gives full control over transactions at the JDBC level.