Search code examples
springspring-dataspring-data-mongodbspring-transactions

How to use transactions with Spring Data MongoRepository?


I have an interface extending MongoRepository<Thing, String> and also created a MongoConfig that extends AbstractMongoClientConfiguration. In the config, there is a @Bean MongoTransactionManager (no special settings used, everything is default).

Despite all this, when I try the following code:

    @Transactional(transactionManager = "mongoTransactionManager")
    void transactionalTest() {
      notes.save(new Thing("1"));
      fail();
      notes.save(new Thing("2"));
    }
    
    private void fail() {
      throw new RuntimeException("Failure to test transactionality.");
    }

I end up with "Thing 1" in my DB. My expectation would be to see nothing there (as I marked the function with the two saves as transactional).

What am I missing?

[*] trying to follow https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative-annotations


Solution

  • I know I am little late for the party but I think it'd be good idea to post the answer anyway.

    Its only a 2 step process:

    1. Put these configurations in MongoConfig file:

      @Configuration
      public class MongoConfig {
      
      @Bean
      MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
          return new MongoTransactionManager(dbFactory);
          }
      }
      
    2. Put @Transactional annotation on the service method which you want to be considered as one transaction like this:

      @Transactional
      void transactionalTest() {
          notes.save(new Thing("1"));
          fail();
          notes.save(new Thing("2"));
      }
      
      private void fail() {
          throw new RuntimeException("Failure to test transactionality.");
      }
      
      
      private void fail() {
          throw new RuntimeException("Failure to test transactionality.");
      }
      
    • Code level changes are done. Now we need to check the server configurations.
    1. Go to mongo configuration file (I used this method to configure my brew installed mongodb: https://silvae86.github.io/2021/03/04/migrate-mongodb-from-single-to-replicaset/)