Sub topic 9
Reactive data access with repositories
This chapter assumes you can write a Spring Boot @RestController, that you know what Mono and Flux represent, and that you have seen map and flatMap. It covers how a repository fits into a non-blocking pipeline and what breaks when it doesn't.
Why the database driver matters
A WebFlux service has a few event-loop threads. If a handler calls a blocking database driver, that thread waits for the query and can't serve other requests. A reactive endpoint over a blocking driver loses most of its benefit.
JDBC, and therefore JPA and Hibernate, is blocking. Every call parks the calling thread until the database answers. To keep the whole request path non-blocking you need a driver that uses non-blocking I/O and returns Publisher types. Spring Data provides reactive repositories on top of such drivers.
| Store | Spring Data module | Driver style |
|---|---|---|
| PostgreSQL, MySQL, SQL Server, H2 | Spring Data R2DBC | Reactive Relational Database Connectivity |
| MongoDB | Spring Data MongoDB Reactive | MongoDB reactive streams driver |
| Redis | Spring Data Redis Reactive | Lettuce |
| Cassandra, Couchbase, Elasticsearch | Corresponding Spring Data modules | Native reactive clients |
The examples below use MongoDB, so the String ids match the controllers from earlier chapters. The repository programming model is the same for R2DBC.
Setting up
Add the reactive starter. With Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>Point it at a database:
spring.data.mongodb.uri=mongodb://localhost:27017/libraryDefine the entity as a record. Spring Data supports immutable types. When you save a record whose id is null, it creates a new instance with the generated id and returns that instance.
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "books")
public record Book(@Id String id, String title, String author, int year) {}The repository interface
Extend ReactiveCrudRepository and declare the entity type and id type. You write no implementation. Spring Data generates it at startup.
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public interface BookRepository extends ReactiveCrudRepository<Book, String> {
Flux<Book> findByAuthor(String author);
Mono<Book> findByTitleIgnoreCase(String title);
Flux<Book> findByYearGreaterThanOrderByYearAsc(int year);
Mono<Long> countByAuthor(String author);
}The return types follow the same rule as in controllers:
- A method that finds at most one result returns
Mono<T>. - A method that finds many results returns
Flux<T>. - A method that returns nothing meaningful, such as
deleteById, returnsMono<Void>. - A count or an existence check returns
Mono<Long>orMono<Boolean>.
The inherited methods have reactive shapes too:
| Method | Returns |
|---|---|
| `findById(id)` | `Mono<T>` |
| `findAll()` | `Flux<T>` |
| `save(entity)` | `Mono<T>` |
| `saveAll(entities)` | `Flux<T>` |
| `deleteById(id)` | `Mono<Void>` |
| `existsById(id)` | `Mono<Boolean>` |
Derived query names such as findByYearGreaterThanOrderByYearAsc are parsed the same way as in imperative Spring Data. Only the return types differ. Parameters can also be Mono<String> or Flux<String>, and the query waits for the value to arrive. That is rarely worth the added complexity. Resolve the value earlier in the pipeline with flatMap and pass a plain value.
Nothing happens until you subscribe
A repository call returns a description of work. It doesn't do the work. This is the most common error in reactive data code:
public void addBook(Book book) {
repository.save(book); // does nothing: no one subscribed
}The Mono returned by save is discarded, so no insert is ever sent. The fix is to return the Mono and let the framework subscribe. In WebFlux, the framework subscribes to whatever your controller returns.
public Mono<Book> addBook(Book book) {
return repository.save(book);
}The same applies to a deletion you want to run as a side effect. Chain it into the pipeline so it is part of the result.
Replace that with the proper diagram below.
Composing repository calls
Because repository methods return Mono and Flux, you combine them with the operators from earlier chapters. A service layer is a good place to do this.
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
public Mono<Book> rename(String id, String newTitle) {
return repository.findById(id)
.map(b -> new Book(b.id(), newTitle, b.author(), b.year()))
.flatMap(repository::save);
}
public Mono<Void> importAll(List<Book> books) {
return repository.saveAll(books).then();
}
public Flux<String> titlesBy(String author) {
return repository.findByAuthor(author).map(Book::title);
}
}Three details are worth noting:
renameusesmapfor the pure change andflatMapfor the step that returns anotherMono. If the id doesn't exist,findByIdcompletes empty and the rest is skipped. The caller sees an emptyMono.importAllusesthen()to discard the saved books and expose only completion. The inserts still happen, because whoever subscribes to theMono<Void>triggerssaveAll.titlesByreturns aFlux<String>. No list is built in memory, and each title is emitted as its document arrives.
Connect the service to an endpoint, with a create handler beside the earlier read handlers:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<Book> create(@RequestBody Book book) {
return repository.save(book);
}Empty results and 404 responses
An absent row is not an error to the repository. findById completes without emitting. If the controller returns that empty Mono unchanged, WebFlux answers 200 OK with an empty body. When you want a 404, convert the empty case yourself, as the get method in the annotated controller does with switchIfEmpty. For the opposite case, a lookup that must find nothing, use hasElement() or existsById and branch with flatMap.
public Mono<Book> createIfAbsent(Book book) {
return repository.findByTitleIgnoreCase(book.title())
.switchIfEmpty(Mono.defer(() -> repository.save(book)));
}Mono.defer matters here. Without it, repository.save(book) is assembled eagerly while the pipeline is built. Assembling it is harmless because nothing runs until subscription. The defer form states the intent, and it protects you if the fallback is ever replaced by code with side effects at assembly time.
Transactions
Reactive code can't use thread-bound transactions, because a pipeline may hop between threads. Spring stores the transaction in the Reactor context instead. @Transactional still works on a method that returns Mono or Flux, provided a ReactiveTransactionManager exists.
@Transactional
public Mono<Void> transferStock(String fromId, String toId) {
return repository.findById(fromId)
.zipWith(repository.findById(toId))
.flatMap(pair -> repository.saveAll(List.of(pair.getT1(), pair.getT2())).then());
}Check the following before relying on it:
- R2DBC needs
R2dbcTransactionManager, which Spring Boot configures for you. - MongoDB transactions need a replica set. A standalone
mongodrejects them. - You can also use
TransactionalOperatorand call.as(operator::transactional)on a pipeline when you want a boundary smaller than a method.
Limits to know about
Reactive repositories are not drop-in replacements for JPA repositories.
- Spring Data R2DBC is not an ORM. It has no lazy loading, no entity cache, and no automatic joins across relationships. You load related data with a second query and combine the results with
flatMaporzip, or you write a query that joins explicitly. - Schema generation is not provided. Create tables with scripts or a migration tool such as Flyway, which runs over JDBC at startup.
- Paging works with
Pageableparameters, but a reactive method can't returnPage<T>, because it needs a total count that arrives separately. ReturnFlux<T>and issue a separatecount()call if you need a total. - Calling
.block()inside a handler to get a plain value puts you back in the blocking model. Reactor detects this on event-loop threads and throws anIllegalStateExceptionthat saysblock()is not supported.
If your data store has only a blocking driver, don't call it directly from a handler. Wrap it and move it to another thread pool, which the threading chapter covers.
Quick reference of common mistakes
- Calling
saveordeletewithout returning or subscribing to the result. Nothing is stored. - Using
mapwhere the function returns aMono. The result becomesMono<Mono<T>>. UseflatMap. - Collecting a large
Fluxinto a list withcollectList()before returning it. You lose streaming and use memory proportional to the result size. - Expecting a 404 from an empty
findById. You get an empty 200 unless you addswitchIfEmpty. - Expecting
@Transactionalto work on a void method that fires off asavewithout returning itsMono.
Exercise
A teammate writes this method and says it "saves the book and returns it", but no row ever appears in the database. Explain why, and rewrite it so the save happens. public Mono<Book> add(Book book) { repository.save(book); return Mono.just(book); }
Show answer
The Mono returned by repository.save(book) is created and thrown away. Nothing subscribes to it, so no insert is sent. The returned Mono.just(book) is a separate, already-complete value. Return the save pipeline so the framework subscribes to it: public Mono<Book> add(Book book) { return repository.save(book); } This also returns the saved instance, including any generated id, which Mono.just(book) would not contain.
Exercise
A controller method calls repository.findByTitleIgnoreCase(title) and returns the Mono directly. When no book matches, the client receives 200 OK with an empty body. Change the method so it responds with 404 Not Found instead.
Show answer
Add switchIfEmpty with an error signal: return repository.findByTitleIgnoreCase(title) .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))); An empty Mono is a normal completion, so you must convert it into an error before WebFlux can map it to a 404 status.