我有一个 SpringBoot 2 项目,我正在使用带有 MySQL5.7 的休眠数据 jpa
我在以下用例中遇到问题:我有一个调用另一个服务方法的服务方法。如果第二个服务的方法产生运行时异常,第一个方法也被标记为回滚,我不能再提交东西了。我只想回滚第二种方法,并且仍然在第一种方法中提交一些东西。
我尝试使用propagation.NESTED但是hibernate不允许嵌套事务(即使jpaTransactionManager支持它们并且MySQL支持保存点)。
我怎么解决这个问题?我可以以某种方式配置嵌套吗?
请记住,我需要第二种方法来查看第一种提交的更改,因此我无法将第二种方法标记为传播。REQUIRES_NEW
下面是示例代码来澄清我的问题:
FirstServiceImpl.java
@Service
public class FirstServiceImpl implements FirstService
@Autowired
SecondService secondService;
@Autowired
FirstServiceRepository firstServiceRepository;
@Transactional
public void firstServiceMethod() {
//do something
...
FirstEntity firstEntity = firstServiceRepository.findByXXX();
firstEntity.setStatus(0);
firstServiceRepository.saveAndFlush(firstEntity);
...
boolean runtimeExceptionHappened = secondService.secondServiceMethod();
if (runtimeExceptionHappened) {
firstEntity.setStatus(1);
firstServiceRepository.save();
} else {
firstEntity.setStatus(2);
firstServiceRepository.save();
}
}
第二个服务实现.java
@Service
public class SecondServiceImpl implements SecondService
@Transactional
public boolean secondServiceMethod() {
boolean runtimeExceptionHappened = false;
try {
//do something that saves to db but that may throw a runtime exception
...
} catch (Exception ex) {
runtimeExceptionHappened = true;
}
return runtimeExceptionHappened;
}
所以问题是,当 secondServiceMethod() 引发运行时异常时,它回滚其操作(没关系)然后将其返回变量 runtimeExceptionHappened 设置为 false,但是 firstServiceMethod 被标记为仅回滚,然后
firstEntity.setStatus(1);
firstServiceRepository.save();
没有承诺。
既然我不能使用 NESTED 传播,我该如何实现我的目标?
慕森卡
相关分类