我读了这篇文章Spring Transaction Doesn't Rollback,我想我有一个类似的问题。我的代码结构是这样的:
@Service
public class CoreProcessor {
@Transactional
@Scheduled(fixedDelay = 200000)
public void run(){
processingRequest();
}
public boolean processingRequest(JobRequest request){
try{
persistRequest(request);
}
catch(Exception e){
//some code here
throw new Exception();
}
}
private void persistRequest(JobRequest request){
Job job = new Job();
//...some other code to initialize Job using request...
coreProcessorService.persistJob(job); //this updates the job status and saves to db
errorMethod(); // this method throws the error (NullPointerException)
}
}
字符串
对于coreProcessorService类中的persistJob,它非常简单:
@Service
public class CoreProcessorService {
public Job persistJob(Job job){
return JobRepository.save(job);
}
}
型
由于errorMethod()
抛出错误,我希望回滚persistJob()
中的所有更改。但目前它正在更新和保存。如何修复此问题?
我尝试过:将@Transactional
添加到persistRequest()
或persistJob()
或两者。使用@Transactional(rollbackFor = Exception.class)
非常感谢任何帮助!
1条答案
按热度按时间ijxebb2r1#
transaction由
CoreProcessor.run()
方法启动,并且该方法没有抛出异常,这就是为什么它不会回滚。您应该删除catch异常或将整个persist操作用于CoreProcessorService
类,并在此处启动transaction。然后在run方法中捕获异常以发送/记录错误。个字符