spring - TransactionTemplate 与 @Transactional(propagation = Propagation.REQUIRES_NEW)

标签 spring hibernate

有人可以解释为什么第一个单元测试类有效,而第二个测试类因锁定等待超时错误而失败吗?

第一个测试类:

public class Test1 extends AbstractTransactionalJUnit4SpringContextTests {

    @Before
    public void setUp() {
       // do stuff through hibernate to populate database with test data
    }

    @Test
    @Transactional(propagation = Propagation.NEVER)
    public void testDeleteObject() {

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
               // execute sql that deletes data populated in setUp() [i.e. this will require locks on the objects].
            }
        });
    }
}

第二个测试类[获取锁等待超时错误]:

public class Test2 extends AbstractTransactionalJUnit4SpringContextTests {

    @Before
    public void setUp() {
       // do stuff through hibernate to populate database with test data
    }

    @Test
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void testObject() {

    // execute sql that deletes data populated in setUp() [i.e. this will require locks on the objects].

    }
}

我知道第二个测试类失败,因为两个事务正在争夺相同的锁,但由于其 in_progress 事务状态,两个事务都无法放弃锁。我感到困惑的是为什么第一个测试类成功执行了sql。我可能理解错误,但是当 transactionTemplate 执行事务回调时,不是也会创建一个新事务吗?在那种情况下,不应该发生同样的事情(锁等待超时)吗?

最佳答案

TransactionTemplate 默认情况下不会创建新事务。默认传播行为是 PROPAGATION_REQUIRED。在第一种情况下,不存在锁定问题,因为设置和删除是在同一事务中完成的。

您可以通过将 org.springframework.orm.jpa.JpaTransactionManager 类(甚至整个 org.springframework 包)的日志级别设置为 DEBUG 来查看何时创建新事务或重用现有事务。

Javadoc for propagation behaviour

关于spring - TransactionTemplate 与 @Transactional(propagation = Propagation.REQUIRES_NEW),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10361761/

相关文章:

java - 显式加载实体的集合

spring - Tomcat 服务器不工作 "externally"

java - 如何获取Spring事务管理器实例?

java - Spring/Hibernate 集成中的 NPE SessionFactory

java - OSGI 是一个好的选择吗?

java - JPA双向Onetomany json无限循环

java - 崩溃后处理事务

java - 未找到 H2 数据库的 hibernate 表

mysql - 何时使用 Lucene/Hibernate Search

java - hibernate 一对一关系: Unable to delete the child table