ocathern
ocathern

Reputation: 13

Spring WebFlux + ReactiveMongoDB, Can't save entity

I expect that after the execution of the program, Rubber will be saved in the mongo. The result is 200 O.K, but nothing was saved to the database, I suspect that the problem is in the doOnSuccess method. How to use it? Or what else could be the problem?

@PostMapping
public Mono<Rubber> create(@RequestBody Rubber rubber) {
    return rubberService.create(rubber);
}



@Override
public Mono<Rubber> create(Rubber rubber) {
    return Mono.just(rubber)
            .map(rubberToRubberEntityConverter::convert)
            .doOnSuccess(rubberRepository::save)
            .doOnError((throwable) -> Mono.error(new ApplicationException("Can't create ruber :( ", throwable)))
            .map(rubberEntityToRubberConverter::convert);
}



@Repository
public interface RubberRepository extends ReactiveMongoRepository<RubberEntity, String> {
}

Upvotes: 1

Views: 1271

Answers (1)

Michael Berry
Michael Berry

Reputation: 72284

Your reactive chain isn't set up correctly:

return Mono.just(rubber)
        .map(rubberToRubberEntityConverter::convert)
        .doOnSuccess(rubberRepository::save)

You're not actually doing anything reactive here - you're taking a value, wrapping it in a Mono, converting it (synchronously), then performing a side-effect (also synchronously.) In this case, your side-effect is simply setting up the reactive chain to save to the repository (which will return a Mono), but since that Mono is never subscribed to, the save never actually occurs.

Your doOnError() call has a similar issue - you're again returning a Mono rather than performing a side-effect. Instead, you almost certainly want to use onErrorMap() to convert between one error and another.

In short, any time you use doOnSuccess(), doOnError() etc. and use a method that returns a publisher of some description, it's almost always going to be the wrong thing to do. Using Mono.just() is also a hint that you're not starting with a reactive chain - not necessarily wrong in and of itself, but it can be a warning sign that you're not actually creating a "real" reactive chain.

Instead, you probably want something like:

return rubberRepository.save(rubberToRubberEntityConverter.convert(rubber))
        .onErrorMap((throwable) -> new ApplicationException("Can't create rubber :( ", throwable))
        .map(rubberEntityToRubberConverter::convert);

Upvotes: 1

Related Questions