r2dbc: Spring Data R2DBC CRUD, DatabaseClient, reactive transactions and Testcontainers Postgres (post 2)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4VQVEJWetTT1dYzyJ
This commit is contained in:
2026-10-29 04:16:34 +00:00
co-authored by Claude Sonnet 5.5
parent 89358e7b7c
commit 7d7d4e872e
27 changed files with 813 additions and 0 deletions
@@ -0,0 +1,10 @@
package com.ankurm.r2dbc;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
import java.math.BigDecimal;
@Table("account")
public record Account(@Id Long id, String owner, BigDecimal balance) {
}
@@ -0,0 +1,71 @@
package com.ankurm.r2dbc;
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;
import java.math.BigDecimal;
@Service
public class AccountService {
private final DatabaseClient db;
private final TransactionalOperator tx;
public AccountService(DatabaseClient db, ReactiveTransactionManager tm) {
this.db = db;
this.tx = TransactionalOperator.create(tm);
}
private Mono<Long> adjust(long id, BigDecimal delta) {
return db.sql("UPDATE account SET balance = balance + :d WHERE id = :id")
.bind("d", delta).bind("id", id)
.fetch().rowsUpdated();
}
/** Declarative: the returned Mono is wrapped in a transaction by the proxy. */
@Transactional
public Mono<Void> transfer(long from, long to, BigDecimal amount) {
return adjust(from, amount.negate())
.then(adjust(to, amount))
.then();
}
/** Same work, no transaction. The debit commits on its own before the failure. */
public Mono<Void> transferNoTx(long from, long to, BigDecimal amount) {
return adjust(from, amount.negate())
.then(Mono.<Long>error(new IllegalStateException("simulated failure after debit")))
.then(adjust(to, amount))
.then();
}
/** Programmatic: TransactionalOperator wraps exactly the pipeline you hand it. */
public Mono<Void> transferWithOperator(long from, long to, BigDecimal amount, boolean failAfterDebit) {
Mono<Void> work = adjust(from, amount.negate())
.then(failAfterDebit
? Mono.<Long>error(new IllegalStateException("simulated failure after debit"))
: Mono.just(0L))
.then(adjust(to, amount))
.then();
return tx.transactional(work);
}
/** Declarative, failing: the exception rolls the debit back. */
@Transactional
public Mono<Void> transferThenFail(long from, long to, BigDecimal amount) {
return adjust(from, amount.negate())
.then(Mono.<Long>error(new IllegalStateException("simulated failure after debit")))
.then(adjust(to, amount))
.then();
}
public Mono<BigDecimal> balance(long id) {
return db.sql("SELECT balance FROM account WHERE id = :id")
.bind("id", id)
.map(row -> row.get("balance", BigDecimal.class))
.one();
}
}
@@ -0,0 +1,15 @@
package com.ankurm.r2dbc;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
/**
* A plain row. Note what is NOT here: no {@code List<PurchaseOrder>} field, no
* @OneToMany. Spring Data R2DBC maps one row to one object and nothing else.
*/
@Table("customer")
public record Customer(@Id Long id, String name, String email, String tier) {
public static Customer ofNew(String name, String email, String tier) {
return new Customer(null, name, email, tier);
}
}
@@ -0,0 +1,85 @@
package com.ankurm.r2dbc;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Three ways to get "customers with their orders" when there is no
* relationship mapping. Each makes the cost of that choice visible.
*/
@Service
public class CustomerOrderService {
private final CustomerRepository customers;
private final PurchaseOrderRepository orders;
private final DatabaseClient db;
public CustomerOrderService(CustomerRepository customers, PurchaseOrderRepository orders, DatabaseClient db) {
this.customers = customers;
this.orders = orders;
this.db = db;
}
/** Way 1: 1 + N queries. Correct, readable, and one round trip per customer. */
public Flux<CustomerWithOrders> loadNPlusOne() {
return customers.findAll()
.concatMap(c -> orders.findByCustomerId(c.id()).collectList()
.map(list -> new CustomerWithOrders(c, list)));
}
/** Way 2: two queries total, joined in memory. */
public Flux<CustomerWithOrders> loadTwoQueries() {
return customers.findAll().collectList().flatMapMany(cs ->
orders.findAll().collectList().flatMapMany(os -> {
Map<Long, List<PurchaseOrder>> byCustomer = new LinkedHashMap<>();
os.forEach(o -> byCustomer.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o));
return Flux.fromIterable(cs).map(c ->
new CustomerWithOrders(c, byCustomer.getOrDefault(c.id(), List.of())));
}));
}
/** Way 3: one JOIN with DatabaseClient, grouped by hand. */
public Flux<CustomerWithOrders> loadWithJoin() {
return db.sql("""
SELECT c.id AS cid, c.name, c.email, c.tier,
o.id AS oid, o.total
FROM customer c LEFT JOIN purchase_order o ON o.customer_id = c.id
ORDER BY c.id, o.id
""")
.map((row, meta) -> new Object[]{
new Customer(row.get("cid", Long.class), row.get("name", String.class),
row.get("email", String.class), row.get("tier", String.class)),
row.get("oid", Long.class),
row.get("total", BigDecimal.class)})
.all()
.bufferUntilChanged(r -> ((Customer) r[0]).id())
.map(group -> {
Customer c = (Customer) group.get(0)[0];
List<PurchaseOrder> os = group.stream()
.filter(r -> r[1] != null)
.map(r -> new PurchaseOrder((Long) r[1], c.id(), (BigDecimal) r[2]))
.toList();
return new CustomerWithOrders(c, os);
});
}
/** DatabaseClient with a named parameter and an aggregate - SQL stays SQL. */
public Mono<BigDecimal> totalSpent(String email) {
return db.sql("""
SELECT COALESCE(SUM(o.total), 0) AS spent
FROM customer c JOIN purchase_order o ON o.customer_id = c.id
WHERE c.email = :email
""")
.bind("email", email)
.map(row -> row.get("spent", BigDecimal.class))
.one();
}
}
@@ -0,0 +1,23 @@
package com.ankurm.r2dbc;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface CustomerRepository extends ReactiveCrudRepository<Customer, Long> {
/** Derived query: Spring Data builds the SQL from the method name. */
Flux<Customer> findByTier(String tier);
Mono<Customer> findByEmail(String email);
/** Hand-written SQL: R2DBC repositories take plain SQL, not JPQL. */
@Query("SELECT * FROM customer WHERE lower(name) LIKE lower(:pattern) ORDER BY name")
Flux<Customer> searchByName(String pattern);
/** Modifying query: must return {@code Mono<Long>} (rows updated), {@code Mono<Boolean>} or {@code Mono<Void>}. */
@org.springframework.data.r2dbc.repository.Modifying
@Query("UPDATE customer SET tier = :tier WHERE id = :id")
Mono<Long> changeTier(Long id, String tier);
}
@@ -0,0 +1,7 @@
package com.ankurm.r2dbc;
import java.util.List;
/** The aggregate you assemble yourself, because the mapping layer will not. */
public record CustomerWithOrders(Customer customer, List<PurchaseOrder> orders) {
}
@@ -0,0 +1,12 @@
package com.ankurm.r2dbc;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.math.BigDecimal;
/** The child row holds only the foreign key value, never a Customer object. */
@Table("purchase_order")
public record PurchaseOrder(@Id Long id, @Column("customer_id") Long customerId, BigDecimal total) {
}
@@ -0,0 +1,8 @@
package com.ankurm.r2dbc;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
public interface PurchaseOrderRepository extends ReactiveCrudRepository<PurchaseOrder, Long> {
Flux<PurchaseOrder> findByCustomerId(Long customerId);
}
@@ -0,0 +1,9 @@
package com.ankurm.r2dbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class R2dbcDemoApplication {
public static void main(String[] args) { SpringApplication.run(R2dbcDemoApplication.class, args); }
}
@@ -0,0 +1,5 @@
# Boot runs schema.sql through the R2DBC ConnectionFactory (not JDBC) at startup.
spring.sql.init.mode=always
spring.r2dbc.pool.initial-size=5
spring.r2dbc.pool.max-size=20
logging.level.org.springframework.r2dbc=INFO
+22
View File
@@ -0,0 +1,22 @@
DROP TABLE IF EXISTS purchase_order;
DROP TABLE IF EXISTS account;
DROP TABLE IF EXISTS customer;
CREATE TABLE customer (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
tier TEXT NOT NULL DEFAULT 'STANDARD'
);
CREATE TABLE purchase_order (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customer(id),
total NUMERIC(10,2) NOT NULL
);
CREATE TABLE account (
id BIGSERIAL PRIMARY KEY,
owner TEXT NOT NULL,
balance NUMERIC(12,2) NOT NULL CHECK (balance >= 0)
);