0

I have two databases within one Mongo cluster (version 4.4). One of the data bases is kind of staging area for data, i.e. data stored there temporary, enriched, validated, etc. At some point that data has to be copied to permanent db and marked as copied in temp db. I want to do these operations in one transaction.

According to this blog post it should be quite easy to do using mongo-specific code. But the rest of my application is written on top of SpringData (MongoTemplate from spring-data-mongodb-3.0.2.RELEASE.jar). So I'd like to use it in this case as well.

It is possible to define a transaction manager bean in Spring configuration and use it:

  @Bean
  MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
    return new MongoTransactionManager(dbFactory);
  }

But that bean will be tied to single Mongo database (specified in dbFactory), so on practice a transaction will contain only operations that are related to one DB (not both of them).

I found a way to define ChainedTransactionManager and pass two PlatformTransactionManagers as parameters. But as far as I understand it will create two transactions and will rollback remaining transaction if previous fails. That is not what I'm looking for.

Official Spring data docs do not provide any info on native cross-db Mongo transactions that can be used with MongoTemaplate.

So my question is: Is there any way to define a transaction manager that will support multiple MongoDb databases (and allow to modify a data in both dbs in one transaction)?

igor
  • 699
  • 1
  • 9
  • 26

1 Answers1

0

One potential way to implement this is to establish the transaction outside of your processing code (using withTransaction driver helper), which gives you a session object, and have all of your processing code reference the transaction's session. Then your processing code just needs to use the session but it does not need to worry about transactions and it can be part of a transaction along with other components.

I don't know how to do this specifically with spring data though.

D. SM
  • 13,584
  • 3
  • 12
  • 21