将@Transactional 添加到测试用例会导致数据库中的实体不持久化

Adding @Transactional to Testcase leads to not persisted entities in database

我有一些测试类,通常如下所示

@RunWith(SpringJUnit4ClassRunner.class)
@org.springframework.transaction.annotation.Transactional
public class SpringTestRunnerTransactionTest {
 // Some tests which involve inserting data in the db here --> No persisted entries but 
 // entries can be fetched in same transaction
}

它通过了我当前的所有测试(还包括查询已插入同一测试用例中的插入数据)。但是,当我之后检查数据库时,没有持久条目。 在测试方法之上添加 @org.springframework.transaction.annotation.Transactional 注释时也是如此,即

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTestRunnerTransactionTest {
   @org.springframework.transaction.annotation.Transactional
   @Test
   public void test() {
     // Some tests which involve inserting data in the db here --> No persisted entries but 
     // entries can be fetched in same transaction
    }
}

然而,有趣的是,将注释添加到一些虚拟方法中,最终条目被保存在数据库中。 IE。以下 "works":

    @RunWith(SpringJUnit4ClassRunner.class)
    public class SpringTestRunnerTransactionTest {

        @Test
        public void test() {
            abstraction();
        }

        @org.springframework.transaction.annotation.Transactional
        public void abstraction(){
            // Doing all the tests here works fine and the entities 
            // are persisted in the database!!!!!
        }
   }

现在我想知道为什么会这样。我假设在第一种情况下,事务未提交或回滚,但我不明白为什么。或者直接注释测试类和方法是否存在普遍问题?

一些进一步的信息:我正在使用 SpringData JPA/Hibernate/H2 堆栈。

谢谢

默认情况下,事务在 spring 测试中回滚。如果你想提交使用 @TransactionConfiguration(defaultRollback = false) 在 class 级别或 @Rollback(false) 在方法级别。

有关详细信息,请参阅 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations