Outside Spring, how does jOOQ's DSLContext.transactionResult commit, roll back and nest, and why must the lambda use its Configuration argument?
answer
- fallback provider when none is set
- one held connection, auto-commit off
- any Throwable means rollback
- inner blocks get savepoints
- the lambda's own context, not the captured one
basics
~20 sWithout Spring, transactionResult runs on jOOQ's DefaultTransactionProvider: one connection, auto-commit off, commit when the lambda returns, rollback on any Throwable, savepoints for nested calls. Statements must use the lambda's Configuration, or they run on a different connection.
solid answer
~40 sWhen no `TransactionProvider` is configured, `transactionResult` uses jOOQ's `DefaultTransactionProvider`. It derives a copy of the `Configuration` for the block, acquires one connection into it, turns auto-commit off, runs the lambda, and commits when the lambda returns. If the lambda throws any `Throwable`, it rolls back and rethrows: runtime exceptions and errors unchanged, checked exceptions wrapped in jOOQ's `DataAccessException`. Calling `transactionResult` again on the lambda's own context nests the block as a JDBC savepoint, so an inner failure undoes only the inner work. The connection lives in the derived configuration passed to the lambda, so statements must come from `cfg.dsl()`: a captured outer `DSLContext` over a `DataSource` takes another pooled connection, and its writes are not rolled back with the block.
code
java · 19 linesimport org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import static com.example.shop.db.Tables.ORDERS;
import static com.example.shop.db.Tables.ORDER_LINES;
DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES);
int lines = dsl.transactionResult(cfg -> {
DSLContext tx = cfg.dsl(); // bound to the transaction's connection
tx.insertInto(ORDERS, ORDERS.ID, ORDERS.CUSTOMER_ID)
.values(orderId, customerId)
.execute();
// calling dsl.insertInto(...) here would use another pooled connection
return tx.insertInto(ORDER_LINES, ORDER_LINES.ORDER_ID, ORDER_LINES.SKU)
.values(orderId, sku)
.execute();
});go deeper
Recall that transactionResult runs a lambda as one transaction, commits when it returns and rolls back when it throws.
Explain DefaultTransactionProvider's steps: derived configuration, one held connection, auto-commit off, rollback on any Throwable, savepoints for nested calls on the lambda's context.
Diagnose writes that survive a failed block by spotting a captured outer DSLContext, and explain why a nested call on that context starts a second top-level transaction.
Decide whether a codebase passes the transaction's Configuration down explicitly or opts into thread-bound context, and what each costs in readability and testability.
## What transactionResult does `DSLContext.transactionResult(TransactionalCallable<T>)` runs a lambda as one unit of work and returns the lambda's value; `transaction(TransactionalRunnable)` is the same without a result. jOOQ does not implement the transaction itself: it hands begin, commit and rollback to the **`TransactionProvider`** held by the context's `Configuration`. When no provider has been set, which is the normal case for a context built with `DSL.using(dataSource, dialect)` outside Spring, jOOQ falls back to **`DefaultTransactionProvider`**, which works directly on a JDBC `Connection`. For each call jOOQ first **derives a copy of the `Configuration`** scoped to this transaction and passes that copy to your lambda as its argument. That detail drives the most common bug, described below. ## The lifecycle on DefaultTransactionProvider 1. **Begin.** The provider acquires one connection from the `ConnectionProvider` and keeps it in the derived configuration for the whole block. If the connection is in auto-commit mode, it switches auto-commit off. Requested `TransactionProperty` values, such as `Isolation.SERIALIZABLE` or `Readonly.READONLY`, are applied to the connection at this point. 2. **Run.** Your lambda executes. Every statement created from the lambda's `Configuration` runs on the held connection. 3. **Commit.** If the lambda returns normally, the provider calls `Connection.commit()`. 4. **Rollback.** If the lambda throws **any `Throwable`**, checked or unchecked, the provider calls `Connection.rollback()` and the exception propagates. A `RuntimeException` or `Error` is rethrown as it is; a checked exception comes back wrapped in jOOQ's `org.jooq.exception.DataAccessException`. 5. **Clean up.** Either way, the original auto-commit, isolation and read-only values are restored and the connection is released. There is no rule that a checked exception commits: in jOOQ's model, every exception that escapes the lambda means rollback. ## Nesting with savepoints `DefaultTransactionProvider` supports nested blocks. Call `transactionResult` again on the lambda's own context (`cfg.dsl()`) and the inner block gets a **JDBC savepoint**: - an inner block that returns releases its savepoint, and nothing is committed until the outermost block returns; - an inner block that throws rolls back to its savepoint, undoing only its own work, and rethrows; if the outer lambda catches that exception, the outer transaction can still commit; - savepoints need driver support, and `new DefaultTransactionProvider(connectionProvider, false)` turns nesting off, in which case inner blocks simply join the outer one and a rollback happens only if an exception reaches the outermost block. ## The captured-context trap The lambda's argument is not decoration. The transaction's connection lives in the **derived** configuration, not in the `DSLContext` you called `transactionResult` on. If the lambda uses a captured outer `dsl` instead of `cfg.dsl()` or `DSL.using(cfg)`: - with a `DataSourceConnectionProvider`, each such statement takes **another pooled connection**, is committed on its own (pooled connections normally run in auto-commit mode) and is **not rolled back** with the block; - a "nested" `dsl.transactionResult(...)` on the outer context starts a **new top-level transaction** on yet another connection, not a savepoint. The code compiles and the happy path looks right; the bug shows only when a failure should have undone those writes. The Javadoc of `TransactionalCallable` says transactional code should not depend on captured scope but should derive its transaction context from the `Configuration` argument. Code that does want to capture scope can opt into `ThreadLocalTransactionProvider` together with `ContextTransactionalCallable`, which binds the transaction to the thread instead. ## Comparing the two ways to write the lambda | Inside the lambda | Connection used | Rolled back with the block? | |---|---|---| | `cfg.dsl().insertInto(...)` | the transaction's held connection | yes | | `DSL.using(cfg).insertInto(...)` | the transaction's held connection | yes | | captured `dsl.insertInto(...)` over a `DataSource` | a different pooled connection | no | ## When the provider is not the default Everything above assumes `DefaultTransactionProvider`. If the `Configuration` carries another `TransactionProvider`, `transactionResult` keeps its signature but takes that provider's semantics: under Spring Boot, for instance, it is backed by Spring's transaction manager and asks for a nested transaction. Before reasoning about a block, check which provider the context carries; `dsl.configuration().transactionProvider()` tells you. ## What to say in an interview - `transactionResult` returns the lambda's value; `transaction` returns nothing. - Any `Throwable` rolls back and is rethrown, with checked ones wrapped in jOOQ's `DataAccessException`. - Nested blocks are savepoints, and only when called on the lambda's context. - Use the argument: `cfg.dsl()`, never the captured context.
- What do TransactionProperty arguments to transactionResult do on jOOQ's DefaultTransactionProvider?Passing `Isolation.SERIALIZABLE` or `Readonly.READONLY` makes the provider set that isolation level or read-only flag on the connection when the outermost block begins, and restore the original values when it ends. On a nested call they have no effect, because the outer block has already configured the connection.
- Why does a plain DataSourceConnectionProvider not give you a transaction across two jOOQ statements on its own?It calls `getConnection()` for every execution and `close()` afterwards, so two statements can land on two pooled connections, each committed separately in auto-commit mode. `transactionResult` fixes that by holding one connection for the block with auto-commit off until it ends.
- A checked exception thrown from the transactionResult lambda lets the transaction commit.
- Outside Spring, a captured outer DSLContext inside the lambda joins the transaction automatically.
- A nested transactionResult commits its own work independently of the outer block.
- transactionResult swallows the exception after rolling back and returns null.
- jOOQ needs Spring to run a transaction at all; without it every statement auto-commits.