skip to content

With Spring Boot's jOOQ auto-configuration, an @Transactional order method writes rows and then calls dsl.transactionResult; do they share a connection, and what commits when?

level: seniorimportance: must knowfreq 52%

answer

  1. the proxy hands out the thread's connection
  2. Boot swaps in a Spring-backed provider
  3. PROPAGATION_NESTED, not REQUIRES_NEW
  4. inner commit releases a savepoint
  5. outer boundary decides the outcome

basics

~10 s

Yes, one connection: Boot's TransactionAwareDataSourceProxy hands jOOQ the connection Spring bound to the thread. transactionResult runs on SpringTransactionProvider with PROPAGATION_NESTED, so it becomes a savepoint, and only the outer @Transactional method commits.

solid answer

~40 s

They share one connection. Boot gives jOOQ a `DataSourceConnectionProvider` over a `TransactionAwareDataSourceProxy`, so every statement gets the connection Spring bound to the thread when the `@Transactional` method began. Boot also sets `SpringTransactionProvider`, whose `begin` asks the transaction manager for `PROPAGATION_NESTED`; inside an existing transaction a `DataSourceTransactionManager` creates a savepoint on that same connection. When the lambda returns, jOOQ's commit only releases the savepoint; nothing is durable until the outer method returns and Spring commits. If the lambda throws, say a `DuplicateKeyException` from Boot's exception translator, Spring rolls back to the savepoint and the exception is rethrown: caught, the outer work still commits; uncaught, the whole method rolls back. This is jOOQ 3.21 under Spring Boot 4.1's jOOQ module.

code

java · 28 lines
java
import org.jooq.DSLContext;

import static com.example.shop.db.Tables.COUPON_REDEMPTIONS;
import static com.example.shop.db.Tables.ORDERS;

@Service
class OrderService {
    private final DSLContext dsl;

    OrderService(DSLContext dsl) {
        this.dsl = dsl;
    }

    @Transactional
    public void placeOrder(long orderId, long customerId, String couponCode) {
        dsl.insertInto(ORDERS, ORDERS.ID, ORDERS.CUSTOMER_ID)
           .values(orderId, customerId)
           .execute();
        try {
            dsl.transactionResult(cfg -> cfg.dsl()
                .insertInto(COUPON_REDEMPTIONS, COUPON_REDEMPTIONS.CODE, COUPON_REDEMPTIONS.ORDER_ID)
                .values(couponCode, orderId)
                .execute());
        } catch (DuplicateKeyException alreadyRedeemed) {
            // rolled back to the savepoint; the order row commits with the method
        }
    }
}

go deeper

for a junior

Recall that under Spring Boot jOOQ statements join the @Transactional method's connection, and that transactionResult inside it does not commit on its own.

for a middle

Explain the chain: TransactionAwareDataSourceProxy for the connection, SpringTransactionProvider for the block, PROPAGATION_NESTED turning the block into a savepoint.

for a senior

Walk the failure path precisely: savepoint rollback, the rethrown DuplicateKeyException, and how catching or not catching it decides whether the order row commits.

for a principal

Judge whether nested savepoint blocks belong in the codebase at all, and where an independent commit must instead be a Spring REQUIRES_NEW boundary.

## The setup Boot gives you With Spring Boot's jOOQ auto-configuration, three pieces decide the answer: - The `DSLContext` bean's `ConnectionProvider` is a `DataSourceConnectionProvider` wrapped around a **`TransactionAwareDataSourceProxy`**. Every jOOQ statement asks that proxy for a connection, and the proxy delegates to Spring's `DataSourceUtils`: inside an active Spring transaction it returns the **connection bound to the current thread**, and closing it does not end the transaction. - When a `PlatformTransactionManager` bean exists, Boot sets **`SpringTransactionProvider`** as jOOQ's `TransactionProvider`. Its `begin` asks the transaction manager for a transaction defined with **`PROPAGATION_NESTED`**; its `commit` and `rollback` hand that same transaction status back to the manager. - In a JDBC-only Boot application the transaction manager is a `DataSourceTransactionManager` (Boot may create its `JdbcTransactionManager` subclass), which allows nested transactions by default and implements them with JDBC savepoints. ## Walking through the order service Take an `@Transactional placeOrder(...)` that inserts the order row with the injected `dsl`, then calls `dsl.transactionResult(cfg -> ...)` to record a coupon redemption. 1. Entering `placeOrder`, Spring begins a transaction and binds one connection to the thread. 2. The order insert goes through the proxy and runs on **that connection**. 3. `transactionResult` calls `SpringTransactionProvider.begin`. Because a transaction already exists, `PROPAGATION_NESTED` makes the manager **create a savepoint** on the same connection: no new connection and no new physical transaction. 4. The coupon insert, whether written with `cfg.dsl()` or with the captured `dsl`, also resolves through the proxy to the thread-bound connection. 5. If the lambda returns, jOOQ's commit asks Spring to commit the nested status, which only **releases the savepoint**. Nothing is committed yet. 6. When `placeOrder` returns, Spring commits the outer transaction and both rows become durable together. So the answer to "do they share a connection?" is **yes**, and the answer to "what commits when?" is **only the outer `@Transactional` boundary**. ## The failure path Suppose the coupon code was already redeemed and a unique constraint fires. Boot's exception-translator execute listener turns the `SQLException` into a Spring `DataAccessException`; on PostgreSQL that is a `DuplicateKeyException`. Then: - jOOQ calls `SpringTransactionProvider.rollback`, Spring **rolls back to the savepoint**, and the coupon insert is undone while the order insert stays; - `transactionResult` rethrows the `DuplicateKeyException` unchanged, since it is a `RuntimeException`; - if `placeOrder` catches it, the savepoint rollback has not marked the outer transaction rollback-only, so Spring **commits the order without the coupon**; - if it propagates out of `placeOrder`, Spring's default rule for runtime exceptions rolls back the **whole** transaction, order row included. ## Traps that follow from PROPAGATION_NESTED | Situation | What `transactionResult` does under Boot | |---|---| | Called with no outer Spring transaction | `PROPAGATION_NESTED` acts like `PROPAGATION_REQUIRED`: it starts and commits a real transaction of its own | | Called with `Isolation.SERIALIZABLE` or `Readonly.READONLY` | the argument is ignored, because `SpringTransactionProvider.begin` always builds a plain definition with only the propagation set | | Transaction manager that disallows nesting | throws `NestedTransactionNotSupportedException` when an outer transaction exists; Spring's JPA transaction manager disallows nesting by default | | Statement handed to another thread | that thread has no bound transaction, so the proxy returns a separate pooled connection outside it | Two consequences matter in review: - isolation and read-only belong on the Spring side, for example on `@Transactional`, never on `transactionResult` arguments in a Boot app; - a block meant to commit on its own, such as an audit row that must survive the order failing, cannot be written with `transactionResult` on Boot's default provider; it needs a Spring boundary with `PROPAGATION_REQUIRES_NEW`. ## Proving it in your own service - Spring's transaction manager logs "Creating nested transaction", "Releasing transaction savepoint" and "Rolling back transaction to savepoint" at DEBUG, so one debug run shows which path each block took. - An integration test that forces the duplicate coupon and then counts rows in both tables pins the behaviour down as a regression test. - Reviewing the `transactionResult` calls by their callers, not by their bodies, finds the blocks whose meaning changes with the caller. ## How to answer in one breath Same connection, because the proxy hands jOOQ Spring's thread-bound connection; and `transactionResult` is a savepoint inside the outer transaction, so its commit commits nothing, its rollback undoes only its own block, and the outer `@Transactional` method decides the final outcome. This describes jOOQ 3.21 under Spring Boot 4.1's jOOQ module.

  • Inside the transactionResult lambda under Spring Boot, does it matter whether you use cfg.dsl() or the injected DSLContext?
    For the connection, no: both reach the thread-bound connection through the `TransactionAwareDataSourceProxy`, because `SpringTransactionProvider` keeps no connection of its own in the derived configuration. Still use `cfg.dsl()`: the same code stays correct if it ever runs on jOOQ's `DefaultTransactionProvider`, where a captured context would take a different connection.
  • How would you make the coupon write commit even if the order later fails, in a Boot app using jOOQ?
    Not with `transactionResult`, which is always nested under Boot. Put the write in a separate bean method annotated `@Transactional(propagation = Propagation.REQUIRES_NEW)`, or use a `TransactionTemplate` configured that way. Spring suspends the outer transaction and binds a second connection, and jOOQ statements follow it through the proxy.
  • What changes if the same transactionResult call runs where no @Transactional method is on the stack?
    `PROPAGATION_NESTED` with no existing transaction behaves like `PROPAGATION_REQUIRED`, so Spring starts a real transaction, binds a connection, and commits it when the lambda returns or rolls it back when it throws. The code is identical; its meaning depends on the caller.

A transactionResult block inside @Transactional is like a pencilled amendment to a contract that is still a draft: you can erase the amendment without tearing up the draft, but nothing is binding until the whole contract is signed.

  • transactionResult inside @Transactional opens a second connection and commits on its own.
  • When the transactionResult lambda returns, its rows are already committed to the database.
  • A failing transactionResult block always rolls back the entire outer @Transactional method.
  • Passing Isolation.SERIALIZABLE to transactionResult changes the Spring transaction's isolation level.
  • transactionResult outside any @Transactional method fails because no transaction exists.

Assumes jOOQ 3.21 with Spring Boot 4.1's jOOQ module, where SpringTransactionProvider requests PROPAGATION_NESTED and ignores transaction properties.