CodeGym /Courses /Kotlin SELF /Transactions in JDBC — boundaries, autoCommit, commit/rol...

Transactions in JDBC — boundaries, autoCommit, commit/rollback

Kotlin SELF
Level 59, Lesson 2
Available

1. Why transactions are needed at all

When you write a program, you usually want an action to either happen completely or not happen at all. Not “money was debited but not credited”, not “an expense was added but an entry in the activity log didn’t appear”, not “a user was created but the profile wasn’t created”. In program memory, we often solve this with a normal sequence of operations and checks. But a database lives its own life: it’s a separate world where commands can fail in the middle and some of the changes may already have been saved.

A transaction is a way to tell the database: “Look, a set of commands is about to happen. Treat them as a single atomic action. If everything succeeded — commit. If something broke — roll back as if we did nothing.”

Imagine you’re carrying two cups of coffee: one for yourself and one for a coworker. If you trip, you’d prefer either to deliver both, or (sadly) spill both, but definitely not end up in the situation “you delivered yours, and your coworker is now your enemy for life”. A transaction is like lids on the cups and the rule “carry them together”.

2. autoCommit: why the default mode gets in the way

Before writing a “proper” transaction, you need to understand the setting that is enabled by default in almost all JDBC connections: autoCommit.

In JDBC, Connection has a mode:

  • autoCommit = true — each SQL query is committed immediately, as a separate mini-transaction.
  • autoCommit = false — you manually control when to persist changes (commit()) and when to roll them back (rollback()).

It sounds convenient: “let it commit by itself”. But this is only good while you have one query that is, by itself, the whole action. As soon as an action consists of two or more queries, autoCommit = true turns your “atomic action” into “a chain of independent shots”.

Let’s summarize it in a table — it’s easier to scan:

Mode What happens When it fits Main risk
autoCommit = true
Each query is persisted immediately One query = one action Partially completed scenarios
autoCommit = false
You decide when to persist Multiple queries as one action If you forget commit/rollback, you can get stuck in a weird state

And yes, “forgetting commit()” is a real classic. It’s like writing a thesis but not pressing “Save”. You worked, but there’s no result.

3. Transaction boundaries

Transactions have a subtle point: it’s important not only to “use transactions”, but also to choose their boundaries correctly.

If the transaction is too small, you’ll again get partial execution. If the transaction is too big, you’ll hold the connection and locks longer than needed (and the database will start looking at you suspiciously).

A practical rule for beginners sounds like this:

A transaction should cover only those SQL operations (and the minimal logic around them) that must be consistent with each other.

In our educational console app (let’s say it’s a simple expense tracker ExpenseTracker), a typical consistency example is: we want to add an expense and, at the same time, record an event in the audit table. If the expense is added but the audit record is not, it’s unpleasant: we end up with a “silent” expense that doesn’t show up in the activity history.

Conceptually, the transaction looks like this:

flowchart TD
    A[Started action] --> B[autoCommit = false]
    B --> C[SQL #1]
    C --> D[SQL #2]
    D --> E{Were there errors?}
    E -- no --> F["commit()"]
    E -- yes --> G["rollback()"]
    F --> H[autoCommit back / close]
    G --> H[autoCommit back / close]

The main idea: commit only once, at the end. And rollback() — also only once, if something went wrong.

4. Basic transaction template in JDBC

Now let’s assemble the main template. It will look verbose… but this is one of those cases where verbosity is your insurance against “ghosts in the database”.

Key elements:

  • conn.autoCommit = false — we take control.
  • try { ...; conn.commit() } — run all SQL operations and persist the result.
  • catch { conn.rollback(); throw } — on any error, roll back and rethrow the exception (let the calling code decide what to do).
  • finally { conn.autoCommit = ... } — return the connection to a “normal state” if you plan to reuse it.

By the way, finally as “guaranteed cleanup” is a familiar idea from exception handling: code in finally runs regardless of whether there was an exception.

Mini example: a transaction as a wrapper function

Let’s start with a small but useful utility. It’s not “magic”, it’s just a way to avoid copying the same try/catch/finally all over the project.

import java.sql.Connection

fun <T> inTx(conn: Connection, block: (Connection) -> T): T {
    val oldAutoCommit = conn.autoCommit
    conn.autoCommit = false

    try {
        val result = block(conn)
        conn.commit()
        return result
    } catch (e: Exception) {
        conn.rollback()
        throw e
    } finally {
        conn.autoCommit = oldAutoCommit
    }
}

Notice a bit of “paranoia”: we store the old autoCommit value and restore that exact value, rather than just setting true. This is useful if the connection came to you already in a non-standard mode (in large applications this happens more often than you’d like).

5. Practice: add an expense and write an audit record in one transaction

Now let’s tie this to our ExpenseTracker.

Assume (at the idea level, without diving into DB administration) that we have two tables:

  • expenses(id, amount, category, note)
  • audit_log(id, message)

We want to implement the action “add an expense” so that:

1) the expense is inserted into expenses,

2) the record is inserted into audit_log,

3) if it fails at step 2 — step 1 is rolled back too.

Inserting an expense

Let’s start with the expense insert itself. Here it’s important to remember that executeUpdate() returns the number of affected rows — that’s a great “quick test” that the query actually did something.

import java.sql.Connection

fun insertExpense(conn: Connection, amount: Long, category: String, note: String): Int {
    val sql = "INSERT INTO expenses(amount, category, note) VALUES (?, ?, ?)"

    conn.prepareStatement(sql).use { st ->
        st.setLong(1, amount)
        st.setString(2, category)
        st.setString(3, note)
        return st.executeUpdate()
    }
}

Inserting an audit record

Audit is just a record of “what happened”. In real life, audit can be more complex, but right now we care about the principle of “the second operation”.

import java.sql.Connection

fun insertAudit(conn: Connection, message: String): Int {
    val sql = "INSERT INTO audit_log(message) VALUES (?)"

    conn.prepareStatement(sql).use { st ->
        st.setString(1, message)
        return st.executeUpdate()
    }
}

Combine into a transaction

Now we tie the two operations into one transaction using inTx.

import java.sql.Connection

fun addExpenseWithAudit(conn: Connection, amount: Long, category: String, note: String) {
    inTx(conn) { c ->
        val inserted1 = insertExpense(c, amount, category, note)
        check(inserted1 == 1) { "Expense insert failed: inserted=$inserted1" }

        val inserted2 = insertAudit(c, "Added expense $amount in category=$category")
        check(inserted2 == 1) { "Audit insert failed: inserted=$inserted2" }
    }

    println("Expense saved") // Expense saved
}

Here check(...) is our “emergency stop”: if we expected 1 row but got 0, it means something went wrong (for example, the table doesn’t exist, constraints failed, or the query is incorrect). We treat that as an error, throw an exception, and inTx will automatically perform rollback().

6. Why you can’t “catch an error and continue” inside a transaction

Sometimes a beginner sees an exception and thinks: “I’ll catch it, print println("oops"), and everything will be fine”. The problem is that a transaction is not a place where you can pretend nothing happened.

If an error occurs inside a transaction, you almost always have only two honest options:

  • roll back and report that the operation was not completed;
  • roll back and retry (but that’s a separate strategy and usually requires careful design).

The purpose of catch in the transaction template is not to “swallow” the error, but to guarantee rollback() and then let the error propagate upward.

And here we again recall a familiar construct: try/catch/finally is not only about error handling, but also a mechanism to guarantee cleanup via finally.

7. Example: transferring money as two linked operations

Expenses are fine, but sometimes you want an example that intuitively “hurts” if it’s only half done. Money transfers are a classic.

Let’s say we have a table accounts(id, balance). A transfer is:

1) decrease the balance of from,

2) increase the balance of to.

If you fail between them, you either “lost money” or “created money”. Both situations are interesting… but usually only for tests, not production.

import java.sql.Connection

fun transfer(conn: Connection, fromId: Long, toId: Long, amount: Long) {
    require(amount > 0) { "Amount must be > 0" }

    inTx(conn) { c ->
        val dec = c.prepareStatement(
            "UPDATE accounts SET balance = balance - ? WHERE id = ?"
        ).use { st ->
            st.setLong(1, amount)
            st.setLong(2, fromId)
            st.executeUpdate()
        }

        check(dec == 1) { "Sender not found: id=$fromId" }

        val inc = c.prepareStatement(
            "UPDATE accounts SET balance = balance + ? WHERE id = ?"
        ).use { st ->
            st.setLong(1, amount)
            st.setLong(2, toId)
            st.executeUpdate()
        }

        check(inc == 1) { "Receiver not found: id=$toId" }
    }
}

Yes, there’s a nuance like “what if the sender doesn’t have enough money”, but that’s application logic (and/or DB-level constraints). For this lecture, it’s more important to see the transaction skeleton: two UPDATEs as one action.

8. Relationship with use {}: closing resources even on rollback

It’s very easy to make a mistake: “If we have a transaction, then use {} is no longer needed”. It is needed — even more than before.

The logic is simple: a transaction is responsible for data consistency, while use {} is responsible for closing resources (PreparedStatement, ResultSet, and sometimes the Connection itself). These are different guarantees, and both are important.

In Kotlin, use {} is conceptually similar to “try/finally, where the resource is closed in finally”. That is, even if an error occurs inside, the resource will be closed. It’s the same guaranteed-cleanup philosophy as finally.

Hence a good style: inside the transaction, close all statements and result sets via use {}, and outside the transaction (or in the inTx wrapper) manage commit()/rollback().

9. Common mistakes when working with transactions in JDBC

Mistake #1: left autoCommit = false and forgot to restore it.
This is one of the nastiest problems because it doesn’t show up immediately. You ran the first query “manually”, and then some other piece of code suddenly also started running in manual mode and began requiring commit(). If the connection is reused, always restore autoCommit in finally. The calmest option is to remember the old value and restore it, like we did in inTx.

Mistake #2: commit() is called too early.
Sometimes you see code like this: do the first UPDATE, immediately commit(), then the second UPDATE, and commit() again. This turns the transaction into two independent actions and brings us back to the “halfway” problem. In a sane design, commit() should be called once — at the end, when all related operations have succeeded.

Mistake #3: forgot to do rollback() in catch.
Catching an exception and not rolling back means leaving the connection in a suspended state where changes have partially “hung”, but are not committed. Then the series begins: “Why is the database behaving weirdly when I didn’t do anything”. The rule is simple: if you manually turned off autoCommit, then any error before commit() should almost always lead to rollback().

Mistake #4: catch an exception and “silence” it, pretending everything is fine.
Sometimes code does catch (e: Exception) { rollback(); println(...) } and continues executing as if the operation succeeded. This is dangerous: the caller thinks everything is OK, but in reality nothing was saved. If you are not designing an explicit operation result (for example, a Boolean or a sealed class), it’s better to rethrow the exception after rollback(). The mechanics of try/catch/finally are precisely what let you do that cleanly.

Mistake #5: the transaction is too wide and includes “everything”.
If you put not only SQL inside the transaction, but also user input, menu printing, network requests, and text parsing, you keep the transaction open longer than necessary. Even if “everything works in educational SQLite”, it’s a bad habit. A transaction should be short: SQL operations + minimal result checks.

Mistake #6: don’t check the result of executeUpdate() and commit “into the void”.
A command like UPDATE ... WHERE id = ? can update 0 rows if that id doesn’t exist. If you then call commit(), formally everything is “successful”, but the business meaning failed. Check the number of affected rows via check(...) or return values and decide whether to treat that as an error.

1
Task
Kotlin SELF, level 59, lesson 2
Locked
Mode switch
Mode switch
1
Task
Kotlin SELF, level 59, lesson 2
Locked
Double write
Double write
1
Task
Kotlin SELF, level 59, lesson 2
Locked
Transaction utility
Transaction utility
1
Task
Kotlin SELF, level 59, lesson 2
Locked
Bank Transfer
Bank Transfer
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION