【问题标题】:How to use transactions with Spring Data MongoRepository?如何在 Spring Data MongoRepository 中使用事务?
【发布时间】:2021-08-27 19:13:54
【问题描述】:

我有一个扩展MongoRepository<Thing, String> 的接口,还创建了一个扩展AbstractMongoClientConfigurationMongoConfig。在配置中,有一个@Bean MongoTransactionManager(没有使用特殊设置,一切都是默认的)。

尽管如此,当我尝试以下代码时:

    @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.");
    }

我的数据库中最终得到了“Thing 1”。 我的期望是在那里什么都看不到(因为我将带有两个保存的函数标记为事务性的)。

我错过了什么?

[*] 尝试关注https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative-annotations

【问题讨论】:

    标签: spring spring-data spring-data-mongodb spring-transactions


    【解决方案1】:

    添加以下处理异常的属性:

    @Transactional(rollbackOn = RuntimeException.class)
    

    更多详情,请查看-Here

    【讨论】:

    • 我知道我误导了你一点。我稍微修改了这个例子,见fail。这样,以下文档适用:“默认情况下,事务将在 RuntimeException 上回滚”(您链接的页面上也有相同的说明)。
    猜你喜欢
    • 2012-03-21
    • 2019-11-01
    • 1970-01-01
    • 2013-08-26
    • 2017-10-24
    • 2014-10-30
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多