Sub topic 9
Reactive data access with repositories
This chapter assumes you know Mono and Flux, the basic operators (map, flatMap, switchIfEmpty), and how an annotated controller returns a publisher. It also assumes you have used Spring Data repositories in a blocking application.
Why the data layer matters
A reactive controller is only as non-blocking as the code beneath it. If a repository call blocks a Netty event-loop thread while it waits for the database, the few threads WebFlux relies on stall, and the benefit of the reactive model is lost.
Spring Data provides reactive repositories for stores that have non-blocking drivers:
- MongoDB, Redis, Cassandra, and Couchbase through their reactive drivers
- Relational databases through R2DBC (Reactive Relational Database Connectivity)
JDBC and JPA are blocking APIs. A JpaRepository is not reactive, even if you wrap its results in a Mono.
The repository interface
ReactiveCrudRepository mirrors CrudRepository, but its methods return Mono for zero or one result and Flux for many. The example below uses MongoDB.
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Document
public record Book(@Id String id, String title, String author) {}
public interface BookRepository extends ReactiveCrudRepository<Book, String> {
Flux<Book> findByAuthor(String author);
Mono<Book> findByTitle(String title);
}Spring Data derives the queries from the method names, as it does in the blocking version. Only the return types change.
Composing repository calls
Repository methods return publishers, so you chain them like any other pipeline. This method looks up a book, changes its title, and saves it.
Mono<Book> rename(String id, String newTitle) {
return repository.findById(id)
.map(book -> new Book(book.id(), newTitle, book.author()))
.flatMap(repository::save)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}Here save returns a Mono<Book>, which is why the pipeline uses flatMap and not map. An empty result from findById is not an error. It is a completion signal with no element, and switchIfEmpty turns it into a 404.
If a database failure should degrade gracefully, handle it in the pipeline:
Mono<Book> safe = repository.findById(id)
.onErrorResume(DataAccessException.class, ex -> Mono.empty());Common errors
- Nothing happens. A
saveordeleteByIdwhose Mono is never subscribed does not run. Return the Mono from your controller or service, or chain it into a pipeline that is returned. - Calling
block(). Reactor throws anIllegalStateExceptionwhen you callblock()on an event-loop thread. Compose with operators instead. - Using
nullfor "not found". Reactive methods never returnnull. UseswitchIfEmptyordefaultIfEmpty. - Using a blocking store. If you must call JDBC or JPA, wrap the call in
Mono.fromCallableand usesubscribeOn(Schedulers.boundedElastic()). This keeps the event loop free, but it still uses a thread per waiting call, so it only works around the problem. - Assigned IDs in R2DBC.
saveon an entity with a non-null@Idruns an update, not an insert. Leave the ID null for generated keys, or useinserton anR2dbcEntityTemplate.
Exercise
A teammate writes Book b = repository.findById(id).block(); inside a WebFlux controller method. Why is this a problem, and what should the method do instead?
Show answer
block() waits for the result on the current thread. On a Netty event-loop thread this stalls the few threads that serve all requests, and Reactor may throw an exception to prevent it. The method should return Mono<Book> from repository.findById(id), adding operators such as map, flatMap, or switchIfEmpty as needed, so the framework subscribes to it.