Available in versions: Dev (3.22)

This documentation is for the unreleased development version of jOOQ. Click on the above version links to get this documentation for a supported version of jOOQ.

R2DBC Connection

Supported by ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

Just like with the JDBC Connection, access to the R2DBC io.r2dbc.spi.Connection is sometimes required from code that would otherwise use jOOQ. If your DSLContext and Configuration is configured with an R2DBC io.r2dbc.spi.Connection or io.r2dbc.spi.ConnectionFactory, you can access (and acquire) an R2DBC Connection reactively, using DSLContext.connectionPublisher(), the reactive counterpart of DSLContext.connectionResult(). Just write:

// Run statements directly with R2DBC, and stream their results
Publisher<String> names = create.connectionPublisher((io.r2dbc.spi.Connection c) -> Flux
    .from(c.createStatement("SELECT first_name FROM author ORDER BY id").execute())
    .flatMap(r -> r.map((row, meta) -> row.get(0, String.class)))
);

The connection is acquired lazily, upon subscription, and it is closed (or released back to its pool) once the Publisher returned by your function completes, fails, or is cancelled. The function may return any reactive streams Publisher, including the ones returned by the R2DBC SPI directly.

When called within a transaction created by DSLContext.transactionPublisher(), the transaction's connection is provided, and it isn't closed by connectionPublisher(). This allows for mixing jOOQ queries with direct R2DBC calls in the same transaction:

create.transactionPublisher((Configuration trx) -> Mono
    .from(trx.dsl()
        .insertInto(AUTHOR, AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
        .values(3, "William", "Shakespeare"))

    // This connection is the transaction's connection, so it sees the uncommitted row
    .thenMany(trx.dsl().connectionPublisher(c -> Flux
        .from(c.createStatement("SELECT count(*) FROM author").execute())
        .flatMap(r -> r.map((row, meta) -> row.get(0, Long.class)))
    ))
);

If no R2DBC ConnectionFactory is configured, the resulting Publisher signals a org.jooq.exception.DetachedException.

Kotlin coroutines

The jooq-kotlin-coroutines extension module offers an equivalent org.jooq.kotlin.coroutines.connectionCoroutine() extension function, which can be used just like transactionCoroutine():

suspend fun countAuthors(): Long? = ctx.connectionCoroutine { c ->
    c.createStatement("SELECT count(*) FROM author")
        .execute()
        .awaitSingle()
        .map { row, _ -> row.get(0, Long::class.javaObjectType) }
        .awaitSingle()
}

Feedback

Do you have any feedback about this page? We'd love to hear it!

The jOOQ Logo