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
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:
Put these configurations in MongoConfig file:
@Configuration
public class MongoConfig {
@Bean
MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
}
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.");
}