Practice: transactions in JDBC
55 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Three habits cause most transaction bugs: a catch block without rollback, a helper that opens its own connection, and read-change-write back. Each passes simple tests and fails only on an error or with two users.
Mistake 1: a catch block without rollback
A sign-up inserts a customer, then an address, in one transaction. Example 1 fails on a bad pincode, yet the customer row is saved, because the catch block only prints.
Example 1 · Mistake: no rollback, and finally commits
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class MistakeNoRollback { static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static int insertCustomer(Connection conn, String name, String email) throws SQLException { String sql = "INSERT INTO customers (full_name, email) VALUES (?, ?)"; try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, name); ps.setString(2, email); ps.executeUpdate(); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); return keys.getInt(1); } } }
static void insertAddress(Connection conn, int customerId, String pincode) throws SQLException { String sql = "INSERT INTO addresses (customer_id, line1, city, state, pincode, is_default) " + "VALUES (?, 'Flat 4B, Lake View Road', 'Kolkata', 'West Bengal', ?, TRUE)"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, customerId); ps.setString(2, pincode); ps.executeUpdate(); } }
static int customersWithEmail(Connection conn, String email) throws SQLException { try (PreparedStatement ps = conn.prepareStatement("SELECT COUNT(*) FROM customers WHERE email = ?")) { ps.setString(1, email); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt(1); } } }
// BUG: the catch block reports the error but never rolls back static void registerBuggy(Connection conn, String email) throws SQLException { conn.setAutoCommit(false); try { int id = insertCustomer(conn, "Rohan Das", email); insertAddress(conn, id, "70012"); // 5 digits: CHECK fails conn.commit(); } catch (SQLException e) { System.out.println("Sign-up failed: error " + e.getErrorCode()); } finally { conn.setAutoCommit(true); // commits the customer row } }
public static void main(String[] args) throws SQLException { String email = "rohan.das@example.com"; try (Connection conn = connect()) { registerBuggy(conn, email); System.out.println("Customers saved with that email: " + customersWithEmail(conn, email));
try (PreparedStatement ps = conn.prepareStatement("DELETE FROM customers WHERE email = ?")) { ps.setString(1, email); ps.executeUpdate(); } } }}Sign-up failed: error 3819 Customers saved with that email: 1
What this code does
- The address INSERT fails the pincode CHECK (error 3819). The catch block only prints, so the customer INSERT is still open.
setAutoCommit(true)infinallycommits it: one customer row exists with no address. The program deletes it at the end so it can run again.
Because the catch block prints and stops, the transaction stays open, and finally calls setAutoCommit(true), which commits it: a customer with no address (error 3819). The fix is always the same three lines: rollback() in the catch, throw e to tell the caller, and a catch that covers RuntimeException too. When you review code, look for every setAutoCommit(false) and check that every path after it ends in commit() or rollback().
Fix the error
Fix the catch block
The failed sign-up must leave no customer row behind. Pick the replacement line.
Replace the highlighted line.
Error
Sign-up failed: error 3819 Customers saved with that email: 1
Mistake 2: one transaction, two connections
A helper takeStock(productId, qty) calls connect() itself. Example 2 places an order that fails and rolls back, but 2 pairs of shoes have already left the stock.
Example 2 · Mistake: a helper with its own connection
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class MistakeTwoConnections { static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
// BUG: a "small helper" that opens its own connection (auto-commit on) static void takeStock(int productId, int qty) throws SQLException { try (Connection own = connect(); PreparedStatement ps = own.prepareStatement( "UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?")) { ps.setInt(1, qty); ps.setInt(2, productId); ps.setInt(3, qty); ps.executeUpdate(); } }
static int stockOf(Connection conn, int productId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) { ps.setInt(1, productId); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt("stock"); } } }
public static void main(String[] args) throws SQLException { int shoes = 13; try (Connection conn = connect()) { System.out.println("Shoes in stock: " + stockOf(conn, shoes)); conn.setAutoCommit(false); try { int orderId; try (PreparedStatement ps = conn.prepareStatement( "INSERT INTO orders (customer_id, address_id) VALUES (7, 9)", Statement.RETURN_GENERATED_KEYS)) { ps.executeUpdate(); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); orderId = keys.getInt(1); } } takeStock(shoes, 2); // committed on its own connection try (PreparedStatement ps = conn.prepareStatement( "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 2, ?)")) { ps.setInt(1, orderId); ps.setInt(2, shoes); ps.setBigDecimal(3, new BigDecimal("-2499.00")); // typo: negative price, CHECK fails ps.executeUpdate(); } conn.commit(); } catch (SQLException e) { conn.rollback(); System.out.println("Order failed: error " + e.getErrorCode() + ", rolled back"); } finally { conn.setAutoCommit(true); } System.out.println("Shoes in stock after the rollback: " + stockOf(conn, shoes));
try (PreparedStatement ps = conn.prepareStatement( "UPDATE products SET stock = stock + 2 WHERE product_id = ?")) { ps.setInt(1, shoes); ps.executeUpdate(); } } }}Shoes in stock: 18 Order failed: error 3819, rolled back Shoes in stock after the rollback: 16
What this code does
takeStockopens its own auto-commit connection, so the stock change is saved at once. The item INSERT then fails (a negative price breaks a CHECK) andconn.rollback()removes only the order row.- Stock went from 18 to 16 with no order behind it. The program adds the 2 pairs back at the end.
The helper runs in auto-commit mode, so its UPDATE is committed immediately, outside the caller's transaction. The fix is a design rule: methods that take part in a transaction receive the Connection as a parameter and never open or close it. The method that called setAutoCommit(false) owns the connection and ends the transaction. The DAO module later in this section builds this rule into the structure of ShopLite.
Find the bug
Find the second connection
Each snippet takes stock inside the order transaction. Tap the wrong line.
The stock change must roll back with the order.
Round 1 of 2Mistake 3: read, change in Java, write back
Two staff members restock the Mi Power Bank at the same moment: one adds 10, the other adds 5. Example 3 reads, adds in Java and writes back, then lets the database add.
Example 3 · Mistake: read, add in Java, write back
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class RestockLostUpdate { static final int POWER_BANK = 7;
static Connection connect() throws SQLException { return DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); }
static int readStock(Connection conn) throws SQLException { try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) { ps.setInt(1, POWER_BANK); try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getInt("stock"); } } }
static void update(Connection conn, String sql, int value) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setInt(1, value); ps.setInt(2, POWER_BANK); ps.executeUpdate(); } }
public static void main(String[] args) throws SQLException { try (Connection a = connect(); Connection b = connect()) { int start = readStock(a); a.setAutoCommit(false); b.setAutoCommit(false);
// Mistake: both staff members read, add in Java, and write the result int seenByA = readStock(a); int seenByB = readStock(b); update(a, "UPDATE products SET stock = ? WHERE product_id = ?", seenByA + 10); a.commit(); update(b, "UPDATE products SET stock = ? WHERE product_id = ?", seenByB + 5); b.commit(); System.out.println("Read-add-write: stock went up by " + (readStock(a) - start) + " (expected 15)");
update(a, "UPDATE products SET stock = ? WHERE product_id = ?", start); // reset a.commit();
// Fix: let the database add to the current value update(a, "UPDATE products SET stock = stock + ? WHERE product_id = ?", 10); a.commit(); update(b, "UPDATE products SET stock = stock + ? WHERE product_id = ?", 5); b.commit(); System.out.println("stock = stock + ?: stock went up by " + (readStock(a) - start));
update(a, "UPDATE products SET stock = ? WHERE product_id = ?", start); a.commit(); } }}Read-add-write: stock went up by 5 (expected 15) stock = stock + ?: stock went up by 15
What this code does
- Both connections read the same stock, add 10 and 5 in Java, and write absolute values; the second write wins, so the stock goes up by only 5.
- With
stock = stock + ?each UPDATE adds to the current value, so both restocks count: up by 15. The program resets the stock after each part.
If each member reads the stock, adds in Java and writes the result, the second write overwrites the first: the stock goes up by 5 instead of 15, with no error. The fix depends on the rule:
- A counter change: let SQL do it,
stock = stock + ?orstock = stock - ? ... AND stock >= ?. - A decision that needs the values in Java first:
SELECT ... FOR UPDATEon the rows, inside the transaction, before deciding.
Predict the output
How far does the stock rise?
The stock is 100. Both staff read it before either one writes.
Round 1 of 2
Each member writes the value computed in Java.
Choosing the right tool
Before writing transaction code, answer four questions. They pick the tool for you; a stricter isolation level is almost never the answer.
- Several statements must succeed together? One connection,
setAutoCommit(false), commit or roll back. - An optional step may fail without spoiling the rest? A savepoint around it.
- A number changes based on its current value? A relative, conditional UPDATE, then check the row count.
- A decision needs rows read in Java first?
SELECT ... FOR UPDATEin a fixed id order, plus a retry on 1213 and 1205.
Next step
Check your understanding
12 quick questions