【问题标题】:Don't understand behavior of nested transactions in Spring不了解 Spring 中嵌套事务的行为
【发布时间】:2016-01-22 17:39:01
【问题描述】:

我的数据库有触发器。它们在创建实体后触发。我想测试一个条件,这取决于触发器执行的结果。所以,我需要能够在我的测试中看到这些结果。但是触发器会在提交后触发,此时事务实际上会回滚。

看来,我需要使用transactionTemplatePROPAGATION_REQUIRES_NEW 创建一个新事务。我尝试过这种方式,并且能够看到触发器执行的结果(太棒了!)。但是这种方式又产生了一个问题:看代码,我试图通过 cmets 来解释一个奇怪的行为。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfiguration.class})
@Transactional
public class ServiceTest {

    @Inject
    private PlatformTransactionManager txManager;

    <...>

    @Before
    public final void setUp() {
        clearDatabase();
    }

    @Test
    public final void testFilter() {
        // Note: here database is empty - was cleared by setUp() method
        TransactionTemplate tt = new TransactionTemplate(txManager);
        tt.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus s) {
                createAndSaveEntity();
            }
        });
        // Here I can see created entity and results of the trigger execution
        // But also I see all entities, which was in the database before setUp()
        // That is very strange! Why they appear if I deleted them?
        <...>
    }
}

PS:我使用 Spring Data Neo4j 4.0.0.RELEASE 和 Neo4j 2.3.1

【问题讨论】:

    标签: spring neo4j spring-data spring-data-neo4j spring-data-neo4j-4


    【解决方案1】:

    Neo4j 不支持嵌套事务。因此,如果事务事件处理程序(我假设您(正确地)将其称为“触发器”)丰富了事务,它需要在beforeCommit() 中这样做,并且它将参与全有或全无操作。测试的最佳选择是让事务提交,断言您需要断言的内容,并在每次测试之前或之后清除数据库。

    (如果您确实针对远程数据库运行,GraphAware RestTest 可能有助于断言和清除。如果您使用嵌入式模式进行测试,请使用GraphUnit。)

    您的问题实际上是不同的。看起来有些东西(比如 SDN Session)在测试运行之间没有得到清除。要么明确地清除它,要么用 @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) 注释你的测试。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2019-07-12
      • 2015-12-29
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多