tovarichML
tovarichML

Reputation: 129

does Spring @transactional work with MongoDB?

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.

Upvotes: 10

Views: 24858

Answers (2)

Mykeul
Mykeul

Reputation: 558

@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

Upvotes: 13

kakabali
kakabali

Reputation: 4033

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

Upvotes: 1

Related Questions