尝试防止内部事务回滚。如果内部事务响应不成功,则外部事务应回滚,但内部事务应保存数据。
@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRES_NEW)
private void test1(Account account) throws Exception {
DOA.save(account);
status = test2(account);
if(status!='SUCCESS'){
throw new Exception("api call failed");
}
}
@Transactional(propagation=Propagation.MANDATORY)
private void test2(Account account) {
response //API Call
DOA.save(response);
return response.status;
}
最佳答案
将内部事务方法配置为Propagation.REQUIRES_NEW
,以便在该方法完成时无论外部事务方法是否回滚,它始终会提交(即保存数据)。
此外,请确保外部方法不会自调用内部方法,因为 @Transactional
在这种情况下不起作用(请参阅 docs 中的方法可见性和 @Transactional 部分)。
它们应该驻留在不同的bean中,外部方法调用内部方法的bean:
@Service
public class Service1 {
@Autowired
private Service2 service2;
@Transactional(rollbackFor=Exception.class)
public void test1(Account account) throws Exception {
DOA.save(account);
status = service2.test2(account);
if(status!='SUCCESS'){
throw new Exception("Api call failed");
}
}
}
@Service
public class Service2{
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void test2(Account account) {
response // API Call
DOA.save(response);
return response.status;
}
}
关于java - 如何在内部事务失败但内部事务应该保存数据的情况下回滚外部事务 Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56143224/