Transactions in Java

Introduction

In database applications, multiple SQL statements are often executed as part of a single logical operation. For example, transferring money from one bank account to another involves deducting money from the sender’s account and adding it to the receiver’s account. If one operation succeeds and the other fails, the database becomes inconsistent.

To prevent such issues, JDBC provides Transaction Management, which ensures that a group of SQL statements is treated as a single unit of work. Either all statements are executed successfully (commit) or all changes are undone (rollback) if an error occurs.

Transactions play a critical role in maintaining data integrity and consistency in applications such as banking systems, e-commerce platforms, payroll systems, inventory management, and reservation systems.

What is a Transaction?

A Transaction is a sequence of one or more SQL statements that are executed as a single unit of work.

A transaction follows the all-or-nothing principle:

  • If all statements execute successfully, the transaction is committed.
  • If any statement fails, the transaction is rolled back, and all previous changes are undone.

This ensures that the database always remains in a consistent state.

Why are Transactions Important?

Without transactions, partial updates can occur, leading to incorrect or inconsistent data.

For example, consider a bank transfer:

  1. Deduct ₹5,000 from Account A.
  2. Add ₹5,000 to Account B.

If the first operation succeeds but the second fails due to a system error, the money disappears from Account A without reaching Account B.

Using a transaction ensures that both operations succeed together or both are canceled.

ACID Properties of Transactions

Transactions follow the ACID principles to guarantee reliable database operations.

Property Description
Atomicity All operations succeed or all fail.
Consistency The database remains in a valid state before and after the transaction.
Isolation Concurrent transactions do not interfere with each other.
Durability Once committed, changes are permanently stored even after a system failure.

Auto-Commit Mode

By default, JDBC enables auto-commit mode.

This means every SQL statement is committed automatically immediately after execution.

Example:


Connection con = DriverManager.getConnection(
        url,
        username,
        password);
System.out.println(con.getAutoCommit());

Output

true

When auto-commit is enabled, every SQL statement becomes an individual transaction.

Disabling Auto-Commit

To manually control transactions, disable auto-commit.


Connection con = DriverManager.getConnection(
        url,
        username,
        password);
con.setAutoCommit(false);

Now, changes will not be saved until commit() is called.

Commit Transaction

The commit() method permanently saves all changes made during the transaction.

Syntax:


con.commit();

Example:


PreparedStatement ps1 =
        con.prepareStatement(sql1);
PreparedStatement ps2 =
        con.prepareStatement(sql2);
ps1.executeUpdate();
ps2.executeUpdate();
con.commit();

If both SQL statements execute successfully, the database stores the changes permanently.

Rollback Transaction

If an error occurs during a transaction, use rollback() to undo all changes.

Syntax:


con.rollback();

Example:


try {
    con.setAutoCommit(false);
    ps1.executeUpdate();
    ps2.executeUpdate();
    con.commit();
} catch(Exception e){
    con.rollback();
}

This restores the database to its previous state.

Complete Transaction Example

Suppose we have an accounts table.


CREATE TABLE accounts(
    account_no INT PRIMARY KEY,
    holder_name VARCHAR(100),
    balance DOUBLE
);

Insert sample records.


INSERT INTO accounts VALUES
(101,'Rahul',50000),
(102,'Amit',30000);

Java program:


INSERT INTO accounts VALUES
(101,'Rahul',50000),
(102,'Amit',30000);
Java program:
import java.sql.*;
public class TransactionExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/company";
        String user = "root";
        String password = "password";
        try (
            Connection con = DriverManager.getConnection(url, user, password)
        ) {
            con.setAutoCommit(false);
            PreparedStatement withdraw = con.prepareStatement(
                "UPDATE accounts SET balance = balance - ? WHERE account_no = ?");
            PreparedStatement deposit = con.prepareStatement(
                "UPDATE accounts SET balance = balance + ? WHERE account_no = ?");
            withdraw.setDouble(1, 5000);
            withdraw.setInt(2, 101);
            withdraw.executeUpdate();
            deposit.setDouble(1, 5000);
            deposit.setInt(2, 102);
            deposit.executeUpdate();
            con.commit();
            System.out.println("Transaction Completed Successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Transaction Completed Successfully.

Using Savepoint

A Savepoint allows you to mark a specific point within a transaction.

If an error occurs later, you can roll back to the savepoint instead of rolling back the entire transaction.

Example:


con.setAutoCommit(false);
Savepoint sp = con.setSavepoint();
ps.executeUpdate();
con.rollback(sp);
con.commit();

This provides more control over complex transactions.

Transaction Workflow


  Java Application
        │
        ▼
Database Connection
        │
        ▼
setAutoCommit(false)
        │
        ▼
Execute SQL Statements
        │
        ▼
     Success?
      /     \
    Yes      No
     │        │
     ▼        ▼
 commit()  rollback()
     │        │
     ▼        ▼
 Database Updated

Transaction Methods

Method Description
setAutoCommit(false) Disables automatic commits
getAutoCommit() Returns the current auto-commit mode
commit() Saves all changes permanently
rollback() Undoes all changes in the current transaction
rollback(Savepoint) Rolls back to a specific savepoint
setSavepoint() Creates a savepoint within the transaction
releaseSavepoint() Removes a savepoint

Advantages of Transactions

Transactions provide several important benefits:

  • Maintain data consistency.
  • Prevent partial updates.
  • Ensure reliable database operations.
  • Support ACID properties.
  • Improve data integrity.
  • Enable rollback in case of failures.
  • Essential for financial and business applications.
  • Work seamlessly with batch processing.

Real-life Example

Imagine an Online Shopping Website.

When a customer places an order, several operations occur:

  1. Reduce product stock.
  2. Create an order record.
  3. Generate an invoice.
  4. Record the payment.
  5. Update the shipping details.

If any operation fails, all previous changes must be rolled back to prevent inconsistent data.

Other applications that heavily rely on transactions include:

  • Banking systems
  • ATM software
  • Airline reservation systems
  • Railway booking systems
  • Hospital billing systems
  • Payroll management
  • Inventory management
  • Insurance claim processing

Best Practices

Follow these best practices when working with transactions:

📖
Best Practices:
  • Disable auto-commit only when manual transaction control is required.
  • Keep transactions as short as possible to reduce database locks.
  • Always call commit() after successful execution.
  • Use rollback() whenever an error occurs.
  • Close all JDBC resources using try-with-resources.
  • Handle SQLException properly and log errors.
  • Use savepoints in complex transactions when partial rollback is needed.
  • Avoid performing unnecessary business logic while a transaction is open.

Common Mistakes

Avoid these common mistakes:

  • Forgetting to disable auto-commit before starting a transaction.
  • Not calling commit() after successful operations.
  • Ignoring exceptions without rolling back.
  • Keeping transactions open for too long.
  • Forgetting to release resources.
  • Assuming auto-commit is disabled by default.
  • Performing unrelated operations within the same transaction.
  • Neglecting to use savepoints when appropriate.

Conclusion

Transactions are one of the most important concepts in JDBC and database programming. They ensure that multiple SQL statements are executed as a single logical unit, protecting the database from inconsistent or partial updates. By using methods such as setAutoCommit(false), commit(), rollback(), and Savepoint, developers can build secure, reliable, and fault-tolerant applications.

Related Java Tutorials