skip to content

How does jOOQ run a query reactively over R2DBC, and how does Kotlin coroutine code consume such a query?

level: middleimportance: nice to knowfreq 30%

answer

  1. queries are Publishers
  2. ConnectionFactory, not DataSource
  3. JDBC fallback still blocks
  4. await and Flow bridges
  5. the coroutines module is small

basics

~10 s

jOOQ's ResultQuery implements the reactive-streams Publisher, so with a DSLContext built from an R2DBC ConnectionFactory, subscribing runs non-blocking. Kotlin code awaits it or turns it into a Flow through kotlinx-coroutines-reactive.

solid answer

~40 s

Every jOOQ `ResultQuery<R>` is also a reactive-streams `Publisher<R>`, and DML implements `Publisher<Integer>` through `RowCountQuery`. Build the context with `DSL.using(connectionFactory, SQLDialect.POSTGRES)` and subscribing executes over R2DBC without blocking. The trap: if the context only has a JDBC source, subscribing still emits rows, but jOOQ reads them from a blocking JDBC cursor on the subscribing thread. Methods like `fetch()` and `fetchLazy()` are marked `@Blocking`; on a context with only an R2DBC `ConnectionFactory` they throw `DetachedException`. In Kotlin, because the query is a `Publisher`, `awaitFirstOrNull()`, `awaitSingle()` or `asFlow()` from kotlinx-coroutines-reactive consume it directly. The `jooq-kotlin-coroutines` module adds `DSLContext.transactionCoroutine`, which runs a suspending block inside a reactive transaction built on `transactionPublisher`.

code

java · 11 lines
java
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;

import static com.example.db.Tables.CUSTOMER;

DSLContext ctx = DSL.using(connectionFactory, SQLDialect.POSTGRES);

// A ResultQuery is a reactive-streams Publisher of records
org.reactivestreams.Publisher<?> customers =
    ctx.selectFrom(CUSTOMER).where(CUSTOMER.COUNTRY.eq("DE"));

go deeper

for a junior

Recall that a jOOQ select query is a Publisher, and that the R2DBC path needs a ConnectionFactory rather than a DataSource.

for a middle

Explain that subscription without a ConnectionFactory falls back to a blocking JDBC cursor, and how awaitFirstOrNull and asFlow consume a query.

for a senior

Detect hidden blocking in a reactive service built on a JDBC context, and keep fetch() out of event-loop code.

for a principal

Decide whether a service is reactive end to end with R2DBC or blocking on JDBC, and avoid mixing the two models in one codebase.

## Queries are Publishers In jOOQ the query object itself is the reactive entry point. The interface declarations make it plain: - `ResultQuery<R>` extends `Publisher<R>` (from the reactive-streams API), alongside `Iterable<R>`. - `RowCountQuery` (inserts, updates, deletes) extends `Publisher<Integer>`, emitting the affected row count. There is no separate reactive DSL. The same `ctx.selectFrom(CUSTOMER).where(...)` you would `fetch()` can be handed to any reactive-streams consumer, which calls `subscribe()`. ## What subscribing actually does What happens on `subscribe()` depends on the connection source of the context: | Context built from | On `subscribe()` | |---|---| | R2DBC `ConnectionFactory`: `DSL.using(connectionFactory, dialect)` | Executes over R2DBC, non-blocking, rows emitted on demand | | JDBC `DataSource` or `Connection` only | Falls back to a blocking JDBC cursor read on the subscribing thread | The second row is the trap worth knowing. In jOOQ 3.21 a query whose configuration has no R2DBC `ConnectionFactory` is served by a legacy blocking subscription: it opens a lazy cursor and calls `fetchNext()` for each requested row. It works, so tests pass, but every request ties up the thread that called `request()`. A reactive service wired to a JDBC `DataSource` therefore blocks its event loop while looking reactive. The blocking-style methods on `ResultQuery`, such as `fetch()`, `fetchLazy()` and `fetchStream()`, carry jOOQ's `@Blocking` annotation, a hint for tools and readers that they are not the reactive path. The reverse mix fails loudly: calling `fetch()` or `execute()` on a context that has only an R2DBC `ConnectionFactory` throws `DetachedException`, whose message says a blocking method was called when only an R2DBC connection factory was configured and suggests subscribing to the query instead. ## Wiring the R2DBC path 1. Add an R2DBC driver for your database and create its `ConnectionFactory`. 2. Create the context with `DSL.using(connectionFactory, SQLDialect.POSTGRES)` (an overload without the dialect guesses it from the factory). 3. Return queries as publishers, or wrap them in your reactive library's types. Bind values work as usual; jOOQ adapts parameter rendering to what the R2DBC driver expects. Rows arrive as the same record types you get on JDBC. ## Demand and backpressure Reactive streams are pull-based: a subscriber calls `request(n)` and the publisher may emit at most `n` items. On the R2DBC path, demand flows through jOOQ's non-blocking subscription to the R2DBC driver, whose own prefetching decides how far ahead rows are read. On the blocking fallback jOOQ honours demand too, but each `request(n)` reads `n` rows synchronously from the JDBC cursor before returning, and the cursor is closed on completion, on error or on cancellation. | Path | Thread behaviour | Fits | |---|---|---| | `fetch()` on JDBC | Blocks the caller until all rows are read | Classic thread-per-request services | | `subscribe()` on R2DBC | Non-blocking, rows on demand | Reactive or coroutine services end to end | | `subscribe()` on JDBC | Blocks the requesting thread per demand | Tests or transitions, not event loops | ## Consuming from Kotlin coroutines Because a query is a `Publisher`, the reactive bridge in kotlinx-coroutines (`kotlinx.coroutines.reactive`) works on it directly: ```kotlin import org.jooq.DSLContext import com.example.db.Tables.CUSTOMER suspend fun findCustomer(ctx: DSLContext, id: Long) = ctx.selectFrom(CUSTOMER).where(CUSTOMER.ID.eq(id)).awaitFirstOrNull() fun allCustomers(ctx: DSLContext) = ctx.selectFrom(CUSTOMER).asFlow() ``` - `awaitFirstOrNull()` / `awaitSingle()` suspend until the first or only row arrives. - `asFlow()` turns the publisher into a cold `Flow`; collection subscribes, and backpressure follows the collector. The same rule applies: only an R2DBC-backed context makes these suspensions non-blocking. With a JDBC context the coroutine still runs a blocking cursor read on whatever thread it is dispatched to. ## What the jooq-kotlin-coroutines module adds The `jooq-kotlin-coroutines` artifact is small. In 3.21 it contains `DSLContext.transactionCoroutine`, in two overloads (with and without a `CoroutineContext`). It runs a suspending block in a transaction by wrapping `transactionPublisher` and awaiting its single result. It does **not** add suspending versions of `fetch()` or `execute()`; fetching from coroutines goes through the `Publisher` bridges above. How reactive transactions relate to a framework's transaction manager is a separate topic. ## Common mistakes - Wiring a reactive service to a JDBC `DataSource` and assuming subscription is non-blocking. - Calling `fetch()` inside a reactive pipeline or a coroutine on an event-loop thread. - Looking for `suspend fun fetch()` in the coroutines module. - Calling `fetch()` on an R2DBC-only context and being surprised by `DetachedException`.

  • In jOOQ, how can a test reveal that a reactive endpoint is accidentally using the blocking JDBC fallback?
    Assert on the connection source: the context should be built from an R2DBC `ConnectionFactory`, not a `DataSource`. At runtime, a blocking-call detector on event-loop threads flags the fallback, because jOOQ then reads a JDBC cursor on the subscribing thread. Results alone cannot reveal it, since the fallback returns correct rows.
  • In jOOQ, what happens if code calls fetch() on a DSLContext built only from an R2DBC ConnectionFactory?
    It throws `DetachedException`. The message explains that a blocking method such as `fetch()` or `execute()` was called while only an R2DBC `ConnectionFactory` was configured, and points to embedding the query in a reactive stream, since `ResultQuery` and `RowCountQuery` are publishers.
  • In jOOQ, what does an UPDATE query emit when you subscribe to it?
    Update, insert and delete queries implement `RowCountQuery`, which is a `Publisher<Integer>`. Subscribing executes the statement and emits the affected row count as one integer, which Kotlin code can read with `awaitSingle()`.

  • Subscribing to a jOOQ query fails unless R2DBC is configured
  • jOOQ has a separate reactive DSL distinct from the normal query API
  • jooq-kotlin-coroutines provides suspending fetch() for every query
  • Any subscription to a jOOQ query is non-blocking
  • Calling fetch() inside a coroutine makes it non-blocking