Spring Data R2DBC: reactive access to SQL databases

R2DBC is a non-blocking API for relational databases, the reactive counterpart of JDBC. Spring wraps it in DatabaseClient, repositories and reactive transactions for WebFlux applications. This page runs each of them against H2, and shows the places where R2DBC behaves differently from JPA, including a save that reports success and writes nothing.

Contents

What R2DBC is, and when it is worth it

JDBC is blocking: a thread that runs a query waits until the database answers. In a servlet application that is fine, because each request has its own thread. In a reactive application built on WebFlux and Netty, a few event-loop threads serve all requests, and one blocked thread stalls many requests at once. R2DBC (Reactive Relational Database Connectivity) is a driver API in which every call returns a Reactive Streams Publisher instead of blocking, so the thread is free while the database works.

Spring builds on R2DBC in layers, much as it builds on JDBC:

The R2DBC stack in Spring
LayerWhat it gives youBest for
R2DBC SPI 1.0 and a driverConnectionFactory, Connection, Statement, all returning publishersDriver code; rarely used directly
DatabaseClient (Spring Framework 5.3, spring-r2dbc)SQL with named parameters and row mapping, like JdbcClientHand-written SQL
R2dbcEntityTemplate (Spring Data R2DBC)Insert, update, select and delete of mapped objects, with a Criteria APIEntity operations without a repository
R2dbcRepository (Spring Data R2DBC)Repositories with derived and @Query methods returning Mono and FluxMost CRUD code

R2DBC is not JPA: there is no persistence context, no lazy loading, no dirty checking and no relationships. Each call maps one table to one class. Choose it when the rest of the application is reactive. A servlet application gains nothing from it, and since Java 21, virtual threads make blocking JDBC cheap in servlet applications too.

The examples use Spring Boot 4.1 with spring-boot-starter-data-r2dbc (Spring Data R2DBC 4.1, R2DBC pool 1.0) and the r2dbc-h2 1.1 driver. Spring Boot configures an in-memory database when no spring.r2dbc.url is set. The programs call block() at the end of each pipeline so that main can print results in order; application code returns the Mono or Flux instead.

DatabaseClient: SQL with publishers

Three cities are inserted and queried with plain SQL. The program also checks the row count after building the insert pipeline but before subscribing to it, to show when the SQL actually runs:

Java
package r2dbc.client;

import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class DatabaseClientBasics {

    record City(String name, int population) {
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(DatabaseClientBasics.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            DatabaseClient db = context.getBean(DatabaseClient.class);
            db.sql("CREATE TABLE city (name VARCHAR(40) PRIMARY KEY, population INT)")
                    .then().block();

            Mono<Long> insert = Flux.fromIterable(List.of(
                            new City("Lisbon", 545000), new City("Porto", 232000),
                            new City("Braga", 193000)))
                    .concatMap(city -> db.sql("INSERT INTO city VALUES (:name, :population)")
                            .bind("name", city.name())
                            .bind("population", city.population())
                            .fetch().rowsUpdated())
                    .reduce(0L, Long::sum);
            System.out.println("Insert pipeline built, rows so far: " + count(db));
            System.out.println("Rows inserted after subscribing: " + insert.block());
            System.out.println("Rows now: " + count(db));

            Flux<City> big = db.sql("SELECT name, population FROM city"
                            + " WHERE population > :min ORDER BY population DESC")
                    .bind("min", 200000)
                    .map((row, meta) -> new City(row.get("name", String.class),
                            row.get("population", Integer.class)))
                    .all();
            big.doOnNext(city -> System.out.println("  received " + city + " on "
                            + (Thread.currentThread().getName().startsWith("main")
                                    ? "main" : "another thread")))
                    .blockLast();
        }
    }

    static Long count(DatabaseClient db) {
        return db.sql("SELECT COUNT(*) AS n FROM city")
                .map(row -> row.get("n", Long.class)).one().block();
    }
}
Output
Insert pipeline built, rows so far: 0
Rows inserted after subscribing: 3
Rows now: 3
  received City[name=Lisbon, population=545000] on main
  received City[name=Porto, population=232000] on main
  • After the insert pipeline was built, the table still had 0 rows. A Mono or Flux describes work; nothing runs until something subscribes, here block().
  • Subscribing ran the three inserts one after another (concatMap keeps them in order and on one connection at a time), and reduce summed the updated-row counts to 3.
  • The query bound :min as a named parameter and mapped each row with row.get(name, type). It returned the two cities over 200,000, largest first.
  • Rows arrived on the main thread. r2dbc-h2 wraps H2's embedded engine and runs on the calling thread; a network driver such as r2dbc-postgresql delivers rows on its own event-loop threads, so code after the query must not assume which thread it runs on.

H2 is convenient for running examples, but it is not a non-blocking database. Its R2DBC driver is meant for tests and demos; measure reactive performance against a real network driver.

Repositories and R2dbcEntityTemplate

Spring Data R2DBC maps a class, often a record, to a table, and generates repositories as Spring Data JPA does. The repository methods return Mono for one result and Flux for many. The SQL each call sends is logged after the inserts:

Java
package r2dbc.repo;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.repository.query.Param;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Flux;

@SpringBootApplication
public class RepositoryAndTemplate {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(RepositoryAndTemplate.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            context.getBean(DatabaseClient.class).sql("CREATE TABLE book (id BIGINT"
                    + " AUTO_INCREMENT PRIMARY KEY, title VARCHAR(50), author VARCHAR(50),"
                    + " pages INT)").then().block();
            BookRepository books = context.getBean(BookRepository.class);
            R2dbcEntityTemplate template = context.getBean(R2dbcEntityTemplate.class);

            Flux.just(new Book(null, "Dune", "Herbert", 412),
                            new Book(null, "Emma", "Austen", 474),
                            new Book(null, "Persuasion", "Austen", 249))
                    .concatMap(books::save)
                    .doOnNext(saved -> System.out.println("saved " + saved))
                    .blockLast();
            LoggingSystem.get(RepositoryAndTemplate.class.getClassLoader())
                    .setLogLevel("org.springframework.r2dbc.core", LogLevel.DEBUG);

            System.out.println("-- derived query, paged");
            System.out.println(books.findByAuthor("Austen",
                    PageRequest.of(0, 1, Sort.by("title"))).collectList().block());
            System.out.println("-- @Query");
            System.out.println(books.titlesLongerThan(400).collectList().block());
            System.out.println("-- R2dbcEntityTemplate with Criteria");
            // the query class shares its name with the imported @Query annotation
            var query = org.springframework.data.relational.core.query.Query.query(
                    Criteria.where("pages").lessThan(300));
            System.out.println(template.select(Book.class).matching(query)
                    .all().collectList().block());
        }
    }
}

@Table
record Book(@Id Long id, String title, String author, int pages) {
}

interface BookRepository extends R2dbcRepository<Book, Long> {
    Flux<Book> findByAuthor(String author, Pageable page);

    @Query("SELECT title FROM book WHERE pages > :pages ORDER BY title")
    Flux<String> titlesLongerThan(@Param("pages") int pages);
}
Output
saved Book[id=1, title=Dune, author=Herbert, pages=412]
saved Book[id=2, title=Emma, author=Austen, pages=474]
saved Book[id=3, title=Persuasion, author=Austen, pages=249]
-- derived query, paged
DefaultDatabaseClient: Executing SQL statement [SELECT "BOOK"."ID", "BOOK"."TITLE", "BOOK"."AUTHOR", "BOOK"."PAGES" FROM "BOOK" WHERE "BOOK"."AUTHOR" = $1 ORDER BY "BOOK"."TITLE" ASC LIMIT 1]
[Book[id=2, title=Emma, author=Austen, pages=474]]
-- @Query
DefaultDatabaseClient: Executing SQL statement [SELECT title FROM book WHERE pages > $1 ORDER BY title]
[Dune, Emma]
-- R2dbcEntityTemplate with Criteria
DefaultDatabaseClient: Executing SQL statement [SELECT "BOOK".* FROM "BOOK" WHERE "BOOK"."PAGES" < $1]
[Book[id=3, title=Persuasion, author=Austen, pages=249]]
  • save of a book with a null id ran an INSERT, and returned a new record with the generated id. Because records cannot be changed, Spring Data created a copy through the constructor.
  • The derived findByAuthor with a Pageable became WHERE "BOOK"."AUTHOR" = $1 ORDER BY "BOOK"."TITLE" ASC LIMIT 1. Repositories return a Flux for a page, not a Page; add a countBy... method when you need the total.
  • The @Query method sent its SQL unchanged, with :pages turned into H2's $1 placeholder, and returned plain strings.
  • R2dbcEntityTemplate built WHERE "BOOK"."PAGES" < $1 from Criteria.where("pages").lessThan(300), without a repository method.

The generated SQL quotes every name, and the table name comes from the class name in upper case, "BOOK". That matters for the second trap further down. The Query class used with the template shares its name with the @Query annotation, which is why the program writes one of them with its full package name.

Reactive transactions

A transfer is two updates that must both happen or neither. The table refuses negative balances, and a second constraint added later caps bob at 50, so that the second update of a transfer can fail after the first succeeded:

Java
package r2dbc.tx;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.ReactiveTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.reactive.TransactionalOperator;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class ReactiveTransactions {

    @Service
    static class Transfers {
        private final DatabaseClient db;

        Transfers(DatabaseClient db) {
            this.db = db;
        }

        Mono<Long> move(String from, String to, int amount) {
            return db.sql("UPDATE account SET balance = balance - :amount WHERE name = :name")
                    .bind("amount", amount).bind("name", from).fetch().rowsUpdated()
                    .then(db.sql("UPDATE account SET balance = balance + :amount"
                                    + " WHERE name = :name")
                            .bind("amount", amount).bind("name", to).fetch().rowsUpdated());
        }

        @Transactional
        public Mono<Long> transfer(String from, String to, int amount) {
            return move(from, to, amount);
        }

        public Mono<Long> transferWithoutTransaction(String from, String to, int amount) {
            return move(from, to, amount);
        }
    }

    static void report(String label, DatabaseClient db, Mono<?> work) {
        String outcome = work.map(rows -> "ok").onErrorResume(e -> Mono.just("failed: "
                + e.getClass().getSimpleName())).block();
        System.out.println(label + " -> " + outcome + ", balances "
                + db.sql("SELECT name || '=' || balance AS b FROM account ORDER BY name")
                        .map(row -> row.get("b", String.class)).all().collectList().block());
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(ReactiveTransactions.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            DatabaseClient db = context.getBean(DatabaseClient.class);
            db.sql("CREATE TABLE account (name VARCHAR(10) PRIMARY KEY,"
                    + " balance INT CHECK (balance >= 0))").then().block();
            db.sql("INSERT INTO account VALUES ('ann', 100), ('bob', 0)").then().block();
            Transfers transfers = context.getBean(Transfers.class);
            System.out.println("Transaction manager: " + context.getBean(
                    ReactiveTransactionManager.class).getClass().getSimpleName());

            report("transfer 30 with @Transactional", db, transfers.transfer("ann", "bob", 30));
            db.sql("ALTER TABLE account ADD CONSTRAINT bob_max CHECK (name <> 'bob'"
                    + " OR balance <= 50)").then().block();
            report("transfer 40, bob over limit, no transaction", db,
                    transfers.transferWithoutTransaction("ann", "bob", 40));
            report("transfer 25, bob over limit, @Transactional", db,
                    transfers.transfer("ann", "bob", 25));

            TransactionalOperator tx = TransactionalOperator.create(
                    context.getBean(ReactiveTransactionManager.class));
            report("transfer 25, bob over limit, TransactionalOperator", db,
                    transfers.move("ann", "bob", 25).as(tx::transactional));
        }
    }
}
Output
Transaction manager: R2dbcTransactionManager
transfer 30 with @Transactional -> ok, balances [ann=70, bob=30]
transfer 40, bob over limit, no transaction -> failed: DataIntegrityViolationException, balances [ann=30, bob=30]
transfer 25, bob over limit, @Transactional -> failed: DataIntegrityViolationException, balances [ann=30, bob=30]
transfer 25, bob over limit, TransactionalOperator -> failed: DataIntegrityViolationException, balances [ann=30, bob=30]
  • Spring Boot configured an R2dbcTransactionManager, the reactive counterpart of DataSourceTransactionManager, so @Transactional works on methods that return a Mono or Flux.
  • The first transfer of 30 succeeded: ann 70, bob 30.
  • Without a transaction, the transfer of 40 took 40 from ann and then failed to give it to bob. Each statement committed on its own, so ann went from 70 to 30 and the 40 disappeared.
  • With @Transactional, the failing transfer of 25 rolled back: balances stayed at 30 and 30.
  • TransactionalOperator does the same for one pipeline in code, with .as(tx::transactional), and also rolled back.

Reactive transactions are not bound to a thread, because a pipeline can move between threads. Spring keeps the transaction in the Reactor context of the subscription instead. Two consequences follow. The transaction covers only the publisher the method returns; work started with a separate subscribe() inside the method runs outside it. And it starts only when that publisher is subscribed to, not when the method is called.

Traps: silent saves, quoted names and lost pipelines

Four things that work in JPA, or seem to, behave differently in R2DBC. None of them throws at startup:

Java
package r2dbc.traps;

import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.annotation.Id;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;

@SpringBootApplication
public class R2dbcTraps {

    static String outcome(Mono<?> work) {
        return work.map(result -> "ok: " + result)
                .onErrorResume(e -> Mono.just(e.getClass().getSimpleName() + ": "
                        + e.getMessage().lines().findFirst().orElse("")))
                .block();
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(R2dbcTraps.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            DatabaseClient db = context.getBean(DatabaseClient.class);
            db.sql("CREATE TABLE tag (id VARCHAR(20) PRIMARY KEY, label VARCHAR(20))")
                    .then().block();
            db.sql("CREATE TABLE note (id BIGINT AUTO_INCREMENT PRIMARY KEY,"
                    + " text VARCHAR(40))").then().block();

            System.out.println("1. save() of a new entity whose id is set by the code");
            System.out.println("   " + outcome(context.getBean(TagRepository.class)
                    .save(new Tag("java", "Java"))));
            System.out.println("   rows in tag: " + db.sql("SELECT COUNT(*) AS n FROM tag")
                    .map(row -> row.get("n", Long.class)).one().block());
            System.out.println("   insert() instead: " + outcome(context.getBean(
                    R2dbcEntityTemplate.class).insert(new Tag("java", "Java"))));
            System.out.println("   rows in tag: " + db.sql("SELECT COUNT(*) AS n FROM tag")
                    .map(row -> row.get("n", Long.class)).one().block());

            System.out.println("2. A table name given in @Table(\"note\")");
            System.out.println("   " + outcome(context.getBean(QuotedNoteRepository.class)
                    .save(new QuotedNote(null, "hello"))));

            System.out.println("3. A pipeline that is never subscribed to");
            context.getBean(NoteRepository.class).save(new Note(null, "lost"));
            System.out.println("   rows in note: " + db.sql("SELECT COUNT(*) AS n FROM note")
                    .map(row -> row.get("n", Long.class)).one().block());

            System.out.println("4. An entity with a collection property");
            db.sql("INSERT INTO note (text) VALUES ('tagged')").then().block();
            System.out.println("   " + outcome(context.getBean(NoteWithTagsRepository.class)
                    .findAll().collectList()));
        }
    }
}

@Table
record Tag(@Id String id, String label) {
}

@Table("note")
record QuotedNote(@Id Long id, String text) {
}

@Table
record Note(@Id Long id, String text) {
}

@Table("NOTE")
record NoteWithTags(@Id Long id, String text, List<Tag> tags) {
}

interface TagRepository extends R2dbcRepository<Tag, String> {
}

interface QuotedNoteRepository extends R2dbcRepository<QuotedNote, Long> {
}

interface NoteRepository extends R2dbcRepository<Note, Long> {
}

interface NoteWithTagsRepository extends R2dbcRepository<NoteWithTags, Long> {
}
Output
1. save() of a new entity whose id is set by the code
   ok: Tag[id=java, label=Java]
   rows in tag: 0
   insert() instead: ok: Tag[id=java, label=Java]
   rows in tag: 1
2. A table name given in @Table("note")
   BadSqlGrammarException: executeMany; bad SQL grammar [INSERT INTO "note" ("TEXT") VALUES ($1)]
3. A pipeline that is never subscribed to
   rows in note: 0
4. An entity with a collection property
   ok: [NoteWithTags[id=1, text=tagged, tags=null]]
  • Case 1: the tag's id is set in code, so Spring Data treated it as an existing row and ran an UPDATE. No row matched, the update changed 0 rows, and save still completed normally with the tag. The table stayed empty. R2dbcEntityTemplate.insert always inserts, and it stored the row. For repositories, implement Persistable and return true from isNew() for new objects, or add a @Version field.
  • Case 2: @Table("note") made Spring Data quote the name exactly, INSERT INTO "note". H2 stores unquoted names in upper case, so the table is NOTE, and the insert failed with BadSqlGrammarException. Write explicit names in the case the database stores them, or turn quoting off with an R2dbcMappingContext bean that calls setForceQuote(false).
  • Case 3: save(...) was called but its Mono was dropped, so nobody subscribed and nothing was written. In a controller, returning the Mono lets WebFlux subscribe; in a service, every publisher must be returned or combined into the one that is.
  • Case 4: the List<Tag> tags property did not fail; it was simply left null. Spring Data R2DBC does not load relationships. Load the related rows with a second query, or a join in @Query mapped by hand.

Configuration and schema setup

Common R2DBC settings in Spring Boot
PropertyUse
spring.r2dbc.urlThe connection URL, such as r2dbc:postgresql://localhost/shop or r2dbc:h2:mem:///test
spring.r2dbc.username, passwordCredentials
spring.r2dbc.pool.initial-size, max-size, max-idle-timeThe r2dbc-pool connection pool, used when it is on the classpath
spring.sql.init.modeRuns schema.sql and data.sql through R2DBC, as for JDBC

Flyway and Liquibase use JDBC, not R2DBC. To run migrations in an R2DBC application, add the JDBC driver as well and set spring.flyway.url (or spring.liquibase.url) with the user and password; the migration runs over JDBC at startup, and the application then uses R2DBC. See the Flyway page.

In tests, avoid block() where you can. StepVerifier from reactor-test subscribes to a publisher and checks each element, the completion signal or the error, so a test also fails when a pipeline emits nothing or never completes. The Reactor testing page shows it in detail, including virtual time for pipelines with delays.

Choosing an API

Which R2DBC API fits which need
NeedUse
CRUD and simple queries in a WebFlux applicationR2dbcRepository with derived methods
Hand-written SQL, joins, reportsDatabaseClient with a row mapper
Inserts with ids assigned in codeR2dbcEntityTemplate.insert, or Persistable on the entity
Dynamic filtersR2dbcEntityTemplate with Criteria
Several statements that succeed or fail together@Transactional on a method returning the publisher, or TransactionalOperator
Relationships, lazy loading, cachingJPA with JDBC in a servlet application; R2DBC does not provide them
A blocking applicationJDBC with Spring Data JPA or JdbcClient

R2DBC fits applications that are reactive end to end; the WebFlux page covers the web side, and the Reactor basics page explains Mono and Flux. For the blocking transaction model that R2DBC transactions mirror, see @Transactional.