I am noob in spring
and mongo
and noSQL
.
I have connected to my mongoDB on local.
However my attempts to save my entity keeps failing.
val a0 = myEntity(name = "my Entity")
repository.save(a0)
My repository extends ReactiveMongoRepository<MyEntity, Long>
.
But when I change it to extend MongoRepository<MyEntity, Long>
, then it works.
What possibly could be the problem?
My database instance is running and working fine. I am guessing that it has to do something with reactive things.
If you use reactive streams, you should be aware that nothing happens until you subscribe:
In Reactor, when you write a
Publisher
chain, data does not start pumping into it by default. Instead, you create an abstract description of your asynchronous process (which can help with reusability and composition).By the act of subscribing, you tie the
Publisher
to aSubscriber
, which triggers the flow of data in the whole chain. This is achieved internally by a single request signal from theSubscriber
that is propagated upstream, all the way back to the sourcePublisher
.
That means that if you use ReactiveMongoRepository
, somewhere along the line you have to subscribe to your reactive stream. This can be done by using the subscribe()
method on any Publisher
. For example, using Java, that would be:
reactiveRepository
.save(myEntity)
.subscribe(result => log.info("Entity has been saved: {}", result));
Additionally, frameworks like Webflux will handle the subscription for you if you write reactive controllers. Using Java that means you could write something like:
@GetMapping
public Mono<MyEntity> save() {
return reactiveRepository.save(myEntity); // subscribe() is done by the Webflux framework
}
Obviously, there's a lot more to reactive programming than just that, and you should be aware that you cannot simply swap MongoRepository
to ReactiveMongoRepository
without adapting to the reactive ecosystem and using reactive programming.
There's an Introduction to Reactive Programming chapter within the Reactor reference guide that might be interesting to read. The earlier quoted documentation also comes from this chapter of the reference guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With