我正在使用Spring Boot和MongoDB开发Web应用程序。我想使服务与@transactional spring批注一起使用,但是我不知道这是否真的有效。 (我以前没有使用过mongoDB)。
我添加了注释,似乎一切运行正常(应用程序运行并且我可以执行所有操作CRUD),但是,我不知道Spring是否忽略了注释并且它像往常一样工作,或者是否真的在考虑事务性。
在其他文章中,我已经看到我应该在配置类中添加一个新bean,以启用Spring和MongoDB之间的事务性。真的有必要吗?,我仅将事务与单个Mongo文档一起使用。
最佳答案
@Transactional仅在spring-data-mongodb 2.1.0及更高版本中有效:
https://docs.spring.io/spring-data/mongodb/docs/2.1.0.RELEASE/api/
确实,您必须添加bean:
@Bean
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
我不知道Spring是否忽略了注释并且它像往常一样工作,还是真的在考虑事务性
为此,您可以在2个数据库更新之间引发异常,并检查是否已回滚第一个更新。
但是,如果您在单个Mongo文档中使用事务,则不需要@Transactional批注:
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
关于java - Spring @transactional与MongoDB一起工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55087184/