如何 在运行方法 时而 不是 在方法后强制在Spring Boot中使用Spring Data强制进行事务提交?
我在这里读到,@Transactional(propagation = Propagation.REQUIRES_NEW)在另一堂课上应该有可能,但对我不起作用。
@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")); } }
一种方法是将TransactionTemplatein 插入到测试类中,删除@Transactional和,@Commit然后将测试方法修改为以下内容:
TransactionTemplate
@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如果您打算将断言添加到刚刚持久化的人员对象上,请使用回调隐式代替。
TransactionCallbackWithoutResult