💡 What is a Transaction in Java?
A transaction is a sequence of operations performed as a single logical unit of work. It must follow the ACID properties:
- Atomicity – All operations succeed or none do.
- Consistency – Data remains in a consistent state before and after.
- Isolation – Concurrent transactions do not affect each other.
- Durability – Once committed, the result stays even during system failures.
💬 Simple Real-World Analogy
Imagine you are transferring money between two bank accounts.
- Deduct from Account A
- Add to Account B
If step 1 succeeds but step 2 fails, the money vanishes! A transaction ensures both steps succeed together, or none are done.
⚙️ Java Transaction in Practice
1. Using JDBC (Java Database Connectivity)
Here’s how you handle transactions in plain Java using JDBC:
import java.sql.*;
public class BankTransaction {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/bank";
String user = "root";
String password = "yourpassword";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
conn.setAutoCommit(false); // Start transaction
try {
// Withdraw from Account A
PreparedStatement ps1 = conn.prepareStatement("UPDATE accounts SET balance = balance - 100 WHERE id = ?");
ps1.setInt(1, 1);
ps1.executeUpdate();
// Deposit into Account B
PreparedStatement ps2 = conn.prepareStatement("UPDATE accounts SET balance = balance + 100 WHERE id = ?");
ps2.setInt(1, 2);
ps2.executeUpdate();
conn.commit(); // If all successful
System.out.println("Transaction committed!");
} catch (SQLException e) {
conn.rollback(); // Rollback on error
System.out.println("Transaction rolled back.");
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
✅ Explanation:
conn.setAutoCommit(false)
: Starts a manual transaction.conn.commit()
: Commits the changes if both steps succeed.conn.rollback()
: Reverts the changes if an error occurs.
🧩 Real-World Examples
📦 1. E-commerce Order Processing
- Deduct product stock.
- Create order record.
- Send invoice.
All of these should happen together or not at all.
🏦 2. Bank Money Transfer
- Debit from sender.
- Credit to receiver.
If either fails, rollback to keep consistency.
🏥 3. Hospital Appointment System
- Book time slot.
- Allocate doctor.
- Notify patient.
If the doctor isn’t available, rollback the booking.
🔧 Using Spring Boot (Advanced Users)
If you’re using Spring Framework, managing transactions becomes easier with @Transactional
.
@Service
public class BankService {
@Autowired
private AccountRepository accountRepo;
@Transactional
public void transferMoney(int fromId, int toId, double amount) {
Account from = accountRepo.findById(fromId).orElseThrow();
Account to = accountRepo.findById(toId).orElseThrow();
from.setBalance(from.getBalance() - amount);
to.setBalance(to.getBalance() + amount);
accountRepo.save(from);
accountRepo.save(to);
}
}
✅ The @Transactional
annotation handles:
- Beginning the transaction
- Committing it if no error
- Rolling back if any exception occurs
📘 Summary
Feature | Description |
---|---|
Transaction | Unit of work with atomic behavior |
ACID | Ensures data safety and consistency |
JDBC | Manual control using commit() & rollback() |
Spring Boot | Use @Transactional for easy management |
Real Use Cases | Bank transfers, orders, appointments, etc. |
✅ Final Thoughts
Java transactions are crucial in building safe, reliable, and error-proof applications. Whether you’re working with JDBC or a framework like Spring, understanding transactions helps avoid data inconsistencies and failures in real-world systems.