What is Transaction Management?
Transaction management is a process that ensures data consistency, reliability, and integrity when multiple operations are performed as part of a single logical unit of work.
A transaction in a database is a sequence of operations performed as a single unit that must either completely succeed or completely fail.
Need for Transaction Management
- Ensures data consistency across multiple operations.
- Prevents data corruption during concurrent access.
- Supports rollback in case of errors or failures.
- Maintains the integrity of the database.
ACID Properties
ACID properties ensure reliable processing of transactions in a database:
| Property | Description | Example |
|---|---|---|
| Atomicity | All operations in a transaction are executed or none are. | Transferring money from one account to another must debit one account and credit another completely or not at all. |
| Consistency | The database remains in a valid state before and after the transaction. | After a transfer, the total balance of both accounts must remain the same. |
| Isolation | Transactions are executed independently of one another. | Two users transferring money simultaneously should not interfere with each other. |
| Durability | Once a transaction is committed, the changes are permanent. | After transferring money, the changes persist even if the system crashes. |
JDBC Transaction Management Example
JDBC allows transaction management by default. The auto-commit mode is enabled, meaning every SQL statement is treated as a transaction. To manage transactions manually:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionManagementExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "root";
String password = "password";
String insertAccount1 = "UPDATE accounts SET balance = balance - 500 WHERE id = 1";
String insertAccount2 = "UPDATE accounts SET balance = balance + 500 WHERE id = 2";
try (Connection connection = DriverManager.getConnection(url, user, password)) {
// Disable auto-commit mode
connection.setAutoCommit(false);
try (PreparedStatement stmt1 = connection.prepareStatement(insertAccount1);
PreparedStatement stmt2 = connection.prepareStatement(insertAccount2)) {
stmt1.executeUpdate();
stmt2.executeUpdate();
// Commit the transaction
connection.commit();
System.out.println("Transaction committed successfully.");
} catch (SQLException e) {
// Rollback the transaction in case of errors
connection.rollback();
System.err.println("Transaction rolled back due to an error: " + e.getMessage());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}