Call 2 different ReactiveMongoRepository under the same spring transaction using @Transactional

327 views Asked by At

Let's have 2 different ReactiveMongoRepository mongo repositories:

@Autowired
private CurrencyRepository currencyRepository;

@Autowired
private CurrencyArchiveRepository currencyArchiveRepository;

And a @Transactional method which call both repositories, chainning their callings in a reactive way:

@Override
@Transactional
public Mono<Void> delete(final String currencyCode) {
  final CurrencyArchive currencyArchive = buildCurrencyArchive();

  return this.currencyArchiveRepository.save(currencyArchive)
      .flatMap(c -> this.currencyRepository.delete(c.getCode()))
      .then();
}

What I want to achieve is executing the 2 repository calls under the same transaction, so that, for instance, if the .delete(...) invocation fails, do the previous .save(...) rollback out of the box. I did different tests and I couldn't find a way to get it working so far.

I don't know if this is even posible in a reactive way, as long as when the execution jumps into the flatmap block the TransactionAspectSupport seems to be lost (checked it with the debugger).

Could you give me some advices of how this could be achieved? Thanks in advance

1

There are 1 answers

1
zlaval On

Mongo transactions are disabled by default. You have to register ReactiveMongoTransactionManager in a config class to enable it.

@Bean
ReactiveMongoTransactionManager transactionManager(ReactiveDatabaseFactory factory){  
    return new ReactiveMongoTransactionManager(factory);
}

After this it should be work properly.