๐ก 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.