在使用postgres的Springboot中未回滚事务

bkhjykvo  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(133)

我读了这篇文章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)
非常感谢任何帮助!

ijxebb2r

ijxebb2r1#

transaction由CoreProcessor.run()方法启动,并且该方法没有抛出异常,这就是为什么它不会回滚。您应该删除catch异常或将整个persist操作用于CoreProcessorService类,并在此处启动transaction。然后在run方法中捕获异常以发送/记录错误。

@Service
public class CoreProcessorService {

  @Transactional
  public void persistRequest(JobRequest request){
    Job job = new Job();
    //...some other code to initialize Job using request...
    jobRepository.save(job);  //this updates the job status and saves to db
    errorMethod(); // this method throws the error (NullPointerException)
  }
}

个字符

相关问题