9

I'm developing a web application with Spring Boot and MongoDB. I want to make the services work with the @transactional spring annotation, but I don't know if that really works. (I didn't work with mongoDB before).

I added the annotation and it seem that everything run fine (The application runs and I can do all operations CRUD), but, I don't know if Spring is ignoring the annotation and it is working as usual, or is really considering the transactionality.

In other post, I have seen that I should add a new bean in the configuration class, in order to enable the transactionlity between Spring and MongoDB. Is it really necessary?, I only use transactions with single Mongo documents.

tovarichML
  • 119
  • 1
  • 2
  • 9
  • [Spring Data MongoDB Reference manual, ยง12.2: Transactions with `MongoTransactionManager` (external link)](https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#_transactions_with_mongotransactionmanager) โ€“ Turing85 Mar 10 '19 at 11:33
  • @Turing85 that doesn't work with spring boot. If I create the bean transactionManager, I can not import the type MongoTransactionManager. This type is in the "spring-data-mongodb" library, while I'm using "spring-boot-starter-data-mongodb". If I add the first one dependency into the project, a ClassNotFoundException is through. โ€“ tovarichML Mar 10 '19 at 11:51

2 Answers2

11

@Transactional works only from spring-data-mongodb version 2.1.0 and higher: https://docs.spring.io/spring-data/mongodb/docs/2.1.0.RELEASE/api/

Indeed you have to add the bean:

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

I don't know if Spring is ignoring the annotation and it is working as usual, or is really considering the transactionality

For this, you can throw an exception between 2 DB updates and check if the first update has been rolled back.

But if you use transactions within a single Mongo document, you don't need the @Transactional annotation:

In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document. MongoDb documentation - Transactions

Mykeul
  • 498
  • 1
  • 6
  • 20
  • I recommend ArithmeticException: / by zero, between 2 db inserts. it worked to check the rollback operation. MongoDbFactory is deprecated, now use MongoDatabaseFactory โ€“ Musculaa Jun 05 '21 at 04:08
1

For Reactive style mongoDB & Spring boot integration the answer I provided here can be useful to people

kakabali
  • 3,824
  • 2
  • 29
  • 58