0
votes

I am using spring-boot-starter-data-mongodb:2.2.1.RELEASE and trying to add transaction support for Mongo DB operations.

I have the account service below, where documents are inserted into two collections accounts and profiles. In case an error occurs while inserting into profile collection, the insertion into accounts should rollback. I have configured Spring transactions using MongoTransactionManager.

@Service
public class AccountService {

  @Transactional
  public void register(UserAccount userAccount) {
    userAccount = accountRepository.save(userAccount);
    UserProfile userProfile = new UserProfile(userAccountDoc.getId());
    userProfile = profileRepository.save(userProfile);
  }
}

Enabled Spring transaction support for MongoDB.

@Configuration
public abstract class MongoConfig extends AbstractMongoConfiguration {

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

As per Spring reference doc https://docs.spring.io/spring-data/mongodb/docs/2.2.1.RELEASE/reference/html/#mongo.transactions that is all required to enable transactions for MongoDB. But this is not working. Insertions into accounts collection are not rolled back in case error occurs while inserting into profiles collection. Any suggestions if I am missing anything?

1

1 Answers

0
votes

I would use command monitoring or examine query logs on the server side to ensure that:

  • session ids are sent with queries/write commands
  • transaction operations are performed (there is no startTransaction command but there is a commitTransaction)