Springboot 中使用 postgres 时事务未回滚

问题描述 投票:0回答:1

我读了这篇文章Spring事务不会回滚,我想我也有类似的问题。我的代码结构是这样的:

@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)

非常感谢您的帮助!

java spring-boot jpa transactions
1个回答
2
投票

事务是由

CoreProcessor.run()
方法启动的,并且该方法没有抛出异常,所以它不会回滚。您应该删除 catch 异常或利用
CoreProcessorService
类的整个持久操作,并在此处启动事务。然后在 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)
  }
}
@Service
public class CoreProcessor {

  @Autowired
  private CoreProcessorService coreProcessorService;

  @Scheduled(fixedDelay = 200000)
  public void run(){
    try {
      coreProcessorService.processingRequest();
    } catch(Exception ex) {
      // handle failer
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.