Transactions
Commit and rollback.
Transactions is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is a Transaction?
A transaction groups several SQL operations into a single all-or-nothing unit.
Either every statement succeeds and the changes are made permanent (commit), or something fails and they are all undone (rollback). This keeps the database consistent.
ACID in One Minute
Transactions provide the ACID guarantees:
- Atomicity — all or nothing.
- Consistency — moves the DB from one valid state to another.
- Isolation — concurrent transactions do not corrupt each other.
- Durability — once committed, changes survive a crash.
Auto-Commit Mode
By default JDBC connections run in auto-commit mode: every statement is its own transaction, committed immediately.
That is fine for single statements, but useless when several writes must succeed together. To control transactions yourself, turn auto-commit off.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/bank";
try (Connection conn = DriverManager.getConnection(url, "app", "secret")) {
System.out.println("Default auto-commit: " + conn.getAutoCommit());
conn.setAutoCommit(false);
System.out.println("Now manual: " + conn.getAutoCommit());
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}Commit and Rollback
With auto-commit off, you decide the boundaries:
conn.commit()makes all pending changes permanent.conn.rollback()discards them.
The classic example is a money transfer: debit one account and credit another. Both must happen, or neither.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/bank";
String debit = "UPDATE account SET balance = balance - ? WHERE id = ?";
String credit = "UPDATE account SET balance = balance + ? WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, "app", "secret")) {
conn.setAutoCommit(false);
try (PreparedStatement d = conn.prepareStatement(debit);
PreparedStatement c = conn.prepareStatement(credit)) {
d.setInt(1, 100); d.setInt(2, 1); d.executeUpdate();
c.setInt(1, 100); c.setInt(2, 2); c.executeUpdate();
conn.commit();
System.out.println("Transfer committed");
} catch (SQLException ex) {
conn.rollback();
System.out.println("Rolled back: " + ex.getMessage());
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}The Rollback-on-Failure Pattern
The structure to memorize:
- Turn off auto-commit.
- Do the work inside an inner
try. - On success call
commit(). - In
catchcallrollback()and rethrow or log.
Without the rollback, a failure could leave the database half-updated.
Simulating Atomicity
Here is the all-or-nothing idea modeled in plain Java so it runs standalone. We apply two updates to a snapshot; if either fails, we restore the snapshot.
public class Main {
public static void main(String[] args) {
int[] balances = {500, 300};
int[] backup = balances.clone();
try {
balances[0] -= 200;
if (balances[0] < 0) throw new IllegalStateException("insufficient funds");
balances[1] += 200;
System.out.println("Commit: " + balances[0] + ", " + balances[1]);
} catch (RuntimeException e) {
balances = backup;
System.out.println("Rollback: " + balances[0] + ", " + balances[1]);
}
}
}Savepoints
A savepoint is a marker inside a transaction. You can roll back to it without discarding the whole transaction.
Savepoint sp = conn.setSavepoint()conn.rollback(sp)undoes only work after that point.
Useful for partial recovery in long transactions.
Isolation Levels
Isolation controls what one transaction sees of another's uncommitted work. JDBC defines levels via conn.setTransactionIsolation(...):
TRANSACTION_READ_COMMITTED— the common default.TRANSACTION_REPEATABLE_READTRANSACTION_SERIALIZABLE— strongest, slowest.
Higher isolation prevents anomalies but reduces concurrency.
Read Anomalies
Lower isolation can allow:
- Dirty read — seeing another transaction's uncommitted change.
- Non-repeatable read — a row changes between two reads.
- Phantom read — new rows appear that match a previous query.
Pick the lowest level that still prevents the anomalies your logic cannot tolerate.
Restore Auto-Commit
If you borrowed the connection from a pool, restore its original state before returning it.
After a manual transaction, set conn.setAutoCommit(true) again (or reset to the value you saw on borrow) so the next user is not surprised by your settings.
Keep Transactions Short
A transaction holds locks until it commits or rolls back. Long transactions block other work and increase deadlock risk.
- Do not perform slow network calls or user prompts inside an open transaction.
- Gather your data first, then open, write, and commit quickly.
Short, focused transactions scale far better.
Quick Check
What is the effect of calling connection.rollback()?
Recap
Transactions give you all-or-nothing safety:
- Turn off auto-commit with
setAutoCommit(false). commit()on success,rollback()on failure.- Use savepoints for partial rollback.
- Tune isolation levels to balance correctness and concurrency.
- Restore auto-commit before returning a pooled connection.
Frequently asked questions
Is the “Transactions” lesson free?
Yes — the full text of “Transactions” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Transactions”?
Commit and rollback. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Transactions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.