fla*_*ash 2 java transactions spring-data spring-data-jpa 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
Laz*_*het 10
使用辅助类org.springframework.test.context.transaction.TestTransaction(自 Spring 4.1 起)。
默认情况下会回滚测试。要真正承诺一个人需要做的
// do something before the commit
TestTransaction.flagForCommit(); // need this, otherwise the next line does a rollback
TestTransaction.end();
TestTransaction.start();
// do something in new transaction
Run Code Online (Sandbox Code Playgroud)
请不要@Transactional在测试方法上使用!如果您忘记在业务代码中启动事务,@Transactional测试将永远检测不到它。
一种方法是将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...");
}
Run Code Online (Sandbox Code Playgroud)
要么
new TransactionCallback<Person>() {
@Override
public Person doInTransaction(TransactionStatus status) {
// ...
return person
}
// ...
});
Run Code Online (Sandbox Code Playgroud)
TransactionCallbackWithoutResult如果您打算将断言添加到刚刚持久化的人员对象上,请使用回调隐式代替。
| 归档时间: |
|
| 查看次数: |
3827 次 |
| 最近记录: |