Scrivio Interview library
DebuggingFoundations5 min read · updated 12 November 2026

A plain JDBC method updates the orders table and then inserts into order_audit. The insert fails, but the order update is still in the database. The code never calls setAutoCommit. Explain what happened and fix the code.

A new JDBC connection starts in autocommit mode, which means every statement is committed as its own transaction the moment it finishes. So the UPDATE of orders was already committed when the INSERT into order_audit failed, and there was nothing left to roll back. The fix is to call setAutoCommit(false), run both statements, commit, and roll back in the catch block, or in Spring to let @Transactional or TransactionTemplate manage the transaction.

Why this question is asked

This bug looks impossible to anyone who assumes that code in one method runs as one unit. It is common in plain JDBC code, in scripts and in older services, and it leaves the database in exactly the half-done state transactions are meant to prevent: an order changed with no audit row. Interviewers ask it to check that we know the JDBC default and how to write a correct transaction by hand, including the cleanup. In this answer, we will recap what autocommit means, reproduce the problem, write the corrected JDBC code, see how Spring does the same for us, and look at what connection pools do with autocommit.

1A Quick Recap of Autocommit

A transaction is a group of statements that the database either applies completely or not at all. In JDBC, autocommit decides who ends transactions. When autocommit is true, the driver commits after every statement, so each statement is its own transaction. When autocommit is false, statements accumulate in one transaction until we call commit() or rollback().

The JDBC specification says a new connection starts with autocommit true. So unless our code, our framework or our pool changes it, every executeUpdate() is permanent as soon as it returns.

2Reproducing the Half-Done Change

Here is the method as written. It looks like one operation, but it is two transactions.

Java
public void cancelOrder(long orderId, String user) throws SQLException {
try (Connection conn = dataSource.getConnection(); // autocommit = true
PreparedStatement upd = conn.prepareStatement("UPDATE orders SET status = 'CANCELLED' WHERE id = ?");
PreparedStatement aud = conn.prepareStatement("INSERT INTO order_audit (order_id, action, by_user) VALUES (?, ?, ?)")) {
upd.setLong(1, orderId);
upd.executeUpdate(); // 1 row, COMMITTED right here
aud.setLong(1, orderId); aud.setString(2, "CANCEL"); aud.setString(3, user);
aud.executeUpdate(); // fails: by_user is NOT NULL and user is null
}
}
// result: orders.status = 'CANCELLED', no row in order_audit
Step throughTwo statements, two transactions
Java codeDriverDatabase
executeUpdate(UPDATE orders)
UPDATE, then COMMIT (autocommit)
1 row, permanent
executeUpdate(INSERT order_audit)
INSERT fails, its own transaction rolls back
SQLException; the UPDATE stays

6 messages in order. Play them, or step through them one at a time.

When the INSERT throws, the exception leaves the method and try-with-resources closes the connection. Even a rollback() at this point would do nothing, because the UPDATE's transaction ended when it committed.

3Fixing It in Plain JDBC

We switch autocommit off so both statements belong to one transaction, commit only after both succeed, and roll back on any failure.

Java
public void cancelOrder(long orderId, String user) throws SQLException {
try (Connection conn = dataSource.getConnection()) {
boolean previous = conn.getAutoCommit();
conn.setAutoCommit(false); // start one transaction
try (PreparedStatement upd = conn.prepareStatement("UPDATE orders SET status = 'CANCELLED' WHERE id = ?");
PreparedStatement aud = conn.prepareStatement("INSERT INTO order_audit (order_id, action, by_user) VALUES (?, ?, ?)")) {
upd.setLong(1, orderId);
upd.executeUpdate(); // 1 row, not committed yet
aud.setLong(1, orderId); aud.setString(2, "CANCEL"); aud.setString(3, user);
aud.executeUpdate(); // fails
conn.commit(); // not reached
} catch (SQLException | RuntimeException e) {
conn.rollback(); // the UPDATE is undone
throw e;
} finally {
conn.setAutoCommit(previous); // leave the connection as we found it
}
}
}
// result: orders.status unchanged, no audit row, caller sees the exception

Notice three details. We catch RuntimeException too, so a bug in our own code also rolls back. We rethrow, so the caller knows the cancel failed. And we restore autocommit in finally, because with a pool the connection is reused by the next caller; most pools reset it anyway, but restoring it ourselves keeps the code correct with any DataSource.

4The Spring Way: Let the Framework Do It

In a Spring application we rarely write this by hand. With @Transactional on the method, or a TransactionTemplate, Spring's DataSourceTransactionManager takes a connection, turns autocommit off, binds the connection to the thread so JdbcTemplate uses it, commits when the method returns, rolls back on a runtime exception, and restores autocommit before returning the connection.

Java
@Transactional
public void cancelOrder(long orderId, String user) {
jdbc.update("UPDATE orders SET status = 'CANCELLED' WHERE id = ?", orderId);
jdbc.update("INSERT INTO order_audit (order_id, action, by_user) VALUES (?, ?, ?)", orderId, "CANCEL", user);
} // DataIntegrityViolationException -> whole transaction rolled back

JdbcTemplate translates the SQLException into Spring's unchecked DataAccessException, which triggers the rollback by default. The usual proxy rule applies: the method must be called from another bean.

5What Connection Pools Do With Autocommit

HikariCP, the default pool in Spring Boot, hands out connections with autoCommit true unless configured otherwise. When a connection is returned, Hikari checks its state: if the borrower left a transaction open with autocommit off, Hikari rolls it back so the next borrower does not inherit half a transaction, and it resets properties the borrower changed, such as autocommit, isolation level and read-only, back to the pool's defaults. So a forgotten commit does not leak changes to the next request, but it does silently lose them, which is why the explicit commit and rollback above matter.

6Follow-up questions

What happens if you call commit() while autocommit is true?

The JDBC specification says commit() should throw an SQLException in autocommit mode, and most drivers do; the PostgreSQL driver reports that it cannot commit when autoCommit is enabled. Some drivers have options to ignore it, so check your driver. Either way, it is a sign that the code thinks it has a transaction when it does not.

Does setAutoCommit(false) send BEGIN to the database?

Not necessarily at that moment. Drivers usually start the transaction lazily, with the first statement, so turning autocommit off costs little. Turning it back on while a transaction is open commits that transaction, according to the JDBC specification.

Is autocommit ever the right choice?

Yes, for single independent statements, such as a read-only lookup or one standalone UPDATE. The problem is only when several statements must succeed or fail together.

7Conclusion

In this answer, we saw that JDBC connections start with autocommit true, so each statement commits on its own and the orders update was permanent before the audit insert failed. The fix in plain JDBC is setAutoCommit(false), both statements, commit(), rollback() in the catch block and autocommit restored in finally, all with try-with-resources. In Spring, @Transactional or TransactionTemplate does the same work, and pools like HikariCP default to autocommit true, roll back open transactions on return and reset changed state.

What to say in the interviewAbout 80 seconds aloud

Open with

JDBC connections start with autocommit set to true, so the driver commits after every single statement. The code never turned it off, so the update of orders was committed the moment executeUpdate returned.

Then, if they want more

When the insert into order_audit failed, only that insert was rolled back, and there was nothing left to undo for the update. To fix it in plain JDBC, I'd get the connection in try-with-resources, call setAutoCommit(false), run the update and the insert, and call commit only after both succeed.

In the catch block, for SQLException and runtime exceptions, I'd call rollback and rethrow so the caller knows it failed. In a finally block I'd restore the previous autocommit value, although the pool would normally reset it. In a Spring application I'd just put @Transactional on the method, or use a TransactionTemplate with JdbcTemplate.

The transaction manager turns autocommit off for the transaction, commits or rolls back, and restores autocommit afterwards. And it's worth knowing that HikariCP hands out connections with autocommit true by default, and if someone returns a connection with an open transaction, the pool rolls it back and resets the state, so forgotten commits get lost rather than leaking.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A plain JDBC method updates the orders table and then inserts into order_audit. The...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/9a8834b132/