小编典典

如何在Spring Boot测试中强制事务提交?

spring-boot

如何 在运行方法 时而 不是 在方法后强制在Spring Boot中使用Spring Data强制进行事务提交?

我在这里读到,@Transactional(propagation = Propagation.REQUIRES_NEW)在另一堂课上应该有可能,但对我不起作用。

有什么提示吗?我正在使用Spring Boot v1.5.2.RELEASE。

@RunWith(SpringRunner.class)
@SpringBootTest
public class CommitTest {

    @Autowired
    TestRepo repo;

    @Transactional
    @Commit
    @Test
    public void testCommit() {
        repo.createPerson();
        System.out.println("I want a commit here!");
        // ...
        System.out.println("Something after the commit...");
    }
}

@Repository
public class TestRepo {

    @Autowired
    private PersonRepository personRepo;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createPerson() {
        personRepo.save(new Person("test"));
    }
}

阅读 1842

收藏
2020-05-30

共1个答案

小编典典

一种方法是将TransactionTemplatein
插入到测试类中,删除@Transactional和,@Commit然后将测试方法修改为以下内容:

...
public class CommitTest {

    @Autowired
    TestRepo repo;

    @Autowired
    TransactionTemplate txTemplate;

    @Test
    public void testCommit() {
        txTemplate.execute(new TransactionCallbackWithoutResult() {

          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
            repo.createPerson();
            // ...
          }
        });

        // ...
        System.out.println("Something after the commit...");
    }

要么

new TransactionCallback<Person>() {

    @Override
    public Person doInTransaction(TransactionStatus status) {
      // ...
      return person
    }

    // ...
});

TransactionCallbackWithoutResult如果您打算将断言添加到刚刚持久化的人员对象上,请使用回调隐式代替。

2020-05-30