Loading Test Data
Learn how to load data through the reactive repository, its drawbacks, and a solution to use a nonreactive CRUD repository.
We'll cover the following...
Let’s use the repository we just created to load some test data.
Using ItemRepository
If we wanted to grab a copy of our delightful ItemRepository
, we’d probably write something like this:
itemRepository.save(new Item("Alf alarm clock", 19.99))
See the problem?
The ReactiveCrudRepository.save()
method returns a Mono<T>
. In this case, it’s Mono<Item>
. Remember, a Mono Reactor type doesn’t actually do anything until we subscribe.
In short, the code above does absolutely nothing. To actually get things moving, we must do this:
itemRepository.save(new Item("Alf alarm clock", 19.99)).subscribe()
Keep in mind that there’s still a problem with this, at least during startup. When Netty is launched, the risk of a subscriber causing the startup thread to deadlock its event loop is very real.
Using a nonreactive CRUD repository
When attempting to do something during the startup of our application, the recommendation is to use a blocking version of Spring Data MongoDB!
Because this is about application startup, and focused on test configuration, it’s okay to allow a little bit of blocking code. That’s as long as it doesn’t escape into production!
The only question is, what are we blocking? The repository we defined earlier extends ReactiveCrudRepository
. We can create a counterpart repository.
interface BlockingItemRepository extends CrudRepository<Item, String> {}
This repository definition is ...