Nearby lessons
16 of 37JDBC - Transaction Management
- What a transaction is and the 'all or none' rule
- The ACID properties of a transaction
- Local vs Global transactions
- The three JDBC steps: setAutoCommit(false), commit, rollback
- Savepoints for partial rollback
Transaction Management is a fundamental part of database programming with JDBC. This lesson explains What is a Transaction?, Local vs Global Transactions and The Three Steps of Transaction Management in JDBC with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
What is a Transaction?
A transaction is a group of related operations combined into one single unit, executed on the rule "either all or none". If every operation succeeds, the whole unit is saved (committed). If even one fails, everything is undone (rolled back).
Classic example — funds transfer:
This is why a transaction must be one unit: partial success is not allowed.
Local vs Global Transactions
| Type | Where operations run | Example |
|---|---|---|
| Local transaction | On the same database | Transfer money between two accounts of the same bank |
| Global transaction | On different databases | Transfer money between accounts of two different banks |
The Three Steps of Transaction Management in JDBC
By default, JDBC runs in auto-commit mode — every SQL statement is saved immediately. To build a transaction, we disable that and control the commit ourselves:
The complete program:
The Three Steps of Transaction Management in JDBC
Savepoints — Partial Rollback
Sometimes you don't want to undo everything. A Savepoint is a marker inside a transaction — you can roll back to that marker instead of to the start.
Program: savepoint in action
Transaction Methods — Quick Table
| Method | What it does |
|---|---|
| con.setAutoCommit(false) | Starts manual control of transactions |
| con.setAutoCommit(true) | Back to automatic saving after every query |
| con.commit() | Permanently saves all changes in the transaction |
| con.rollback() | Undoes all uncommitted changes |
| con.setSavepoint(name) | Puts a marker inside the transaction |
| con.rollback(savepoint) | Undoes changes made after the marker |
| con.releaseSavepoint(sp) | Removes the marker |
- Transaction = related operations as one unit, rule: all or none.
- ACID: Atomicity, Consistency, Isolation, Durability.
- JDBC supports local transactions only; global ones need EJB/Spring.
- Three steps: setAutoCommit(false) -> operations -> commit() or rollback().
- Savepoints allow partial rollback to a marker.
- Without transactions, a failed step leaves the database inconsistent.