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
Spring builds on R2DBC in layers, much as it builds on JDBC:
| Layer | What it gives you | Best for |
|---|---|---|
| R2DBC SPI 1.0 and a driver | ConnectionFactoryConnectionStatement | Driver code; rarely used directly |
DatabaseClientspring-r2dbc | SQL with named parameters and row mapping, like JdbcClient | Hand-written SQL |
R2dbcEntityTemplate | Insert, update, select and delete of mapped objects, with a Criteria | Entity operations without a repository |
R2dbcRepository | Repositories with derived and @QueryMonoFlux | Most 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-r2dbcr2dbc-h2spring.r2dbc.urlblock()mainMonoFlux
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:
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();
}
}
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
orMono describes work; nothing runs until something subscribes, hereFlux .block() - Subscribing ran the three inserts one after another (
keeps them in order and on one connection at a time), andconcatMap summed the updated-row counts to 3.reduce - The query bound
as a named parameter and mapped each row with:min . It returned the two cities over 200,000, largest first.row.get(name, type) - Rows arrived on the
thread.main wraps H2's embedded engine and runs on the calling thread; a network driver such asr2dbc-h2 delivers rows on its own event-loop threads, so code after the query must not assume which thread it runs on.r2dbc-postgresql
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 MonoFlux
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);
}
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]]
of a book with asave id ran annull , and returned a new record with the generated id. Because records cannot be changed, Spring Data created a copy through the constructor.INSERT- The derived
with afindByAuthor becamePageable . Repositories return aWHERE "BOOK"."AUTHOR" = $1 ORDER BY "BOOK"."TITLE" ASC LIMIT 1 for a page, not aFlux ; add aPage method when you need the total.countBy... - The
method sent its SQL unchanged, with@Query turned into H2's:pages placeholder, and returned plain strings.$1 builtR2dbcEntityTemplate fromWHERE "BOOK"."PAGES" < $1 , without a repository method.Criteria.where("pages").lessThan(300)
The generated SQL quotes every name, and the table name comes from the class name in upper case, "BOOK"Query@Query
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:
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));
}
}
}
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
, the reactive counterpart ofR2dbcTransactionManager , soDataSourceTransactionManager works on methods that return a@Transactional orMono .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
, the failing transfer of 25 rolled back: balances stayed at 30 and 30.@Transactional does the same for one pipeline in code, withTransactionalOperator , and also rolled back..as(tx::transactional)
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()
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:
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> {
}
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
. No row matched, the update changed 0 rows, andUPDATE still completed normally with the tag. The table stayed empty.save always inserts, and it stored the row. For repositories, implementR2dbcEntityTemplate.insert and returnPersistable fromtrue for new objects, or add aisNew() field.@Version - Case 2:
made Spring Data quote the name exactly,@Table("note") . H2 stores unquoted names in upper case, so the table isINSERT INTO "note" , and the insert failed withNOTE . Write explicit names in the case the database stores them, or turn quoting off with anBadSqlGrammarException bean that callsR2dbcMappingContext .setForceQuote(false) - Case 3:
was called but itssave(...) was dropped, so nobody subscribed and nothing was written. In a controller, returning theMono lets WebFlux subscribe; in a service, every publisher must be returned or combined into the one that is.Mono - Case 4: the
property did not fail; it was simply leftList<Tag> tags . Spring Data R2DBC does not load relationships. Load the related rows with a second query, or a join innull mapped by hand.@Query
Configuration and schema setup
| Property | Use |
|---|---|
spring.r2dbc.url | The connection URL, such as r2dbc:postgresql://localhost/shopr2dbc:h2:mem:///test |
spring.r2dbc.usernamepassword | Credentials |
spring.r2dbc.pool.initial-sizemax-sizemax-idle-time | The r2dbc-pool |
spring.sql.init.mode | Runs schema.sqldata.sql |
Flyway and Liquibase use JDBC, not R2DBC. To run migrations in an R2DBC application, add the JDBC driver as well and set spring.flyway.urlspring.liquibase.url
In tests, avoid block()StepVerifier
Choosing an API
| Need | Use |
|---|---|
| CRUD and simple queries in a WebFlux application | R2dbcRepository |
| Hand-written SQL, joins, reports | DatabaseClient |
| Inserts with ids assigned in code | R2dbcEntityTemplate.insertPersistable |
| Dynamic filters | R2dbcEntityTemplateCriteria |
| Several statements that succeed or fail together | @TransactionalTransactionalOperator |
| Relationships, lazy loading, caching | JPA with JDBC in a servlet application; R2DBC does not provide them |
| A blocking application | JDBC with JdbcClient |
R2DBC fits applications that are reactive end to end; the MonoFlux