Spring注释事务回滚完成不适用于两个表

时间:2018-06-05 07:47:10

标签: java spring

我遇到一个问题,如果有两个insert语句且第二个插入查询中有异常,则回滚无法正常工作。

为表PatientDemographics成功插入1成功
为表EncounterHistory FAILS

插入2

然后插入1的结果不应该回滚(不自动从数据库恢复,而是在数据库中插入记录)。

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void addPatientDemographicsAndEncounterHistory(PatientDemographicsDTO patientDemographicsDTO, int count) throws  Exception{
// save patient demographics data
PatientDemographics patientDemographics = new PatientDemographics();
patientDemographics.setFullName(patientDemographicsDTO.getFullName());
patientDemographics.setMedicalRecordNumber(patientDemographicsDTO.getMedicalRecordNumber());
mednetDAO.saveOrUpdate(patientDemographics);

if(count == 1){
    throw new Exception(count+" Records Saved");
}
// save patient encounter history
EncounterHistory encounterHistory = new EncounterHistory();
encounterHistory.setCompanyID(patientDemographics.getDefaultCompanyID());
encounterHistory.setPatientID(patientDemographics.getPersonID());
encounterHistory.setDepartmentID(patientDemographics.getLastDepartmentID());
encounterHistory.setDoctorID(patientDemographics.getLastDoctorID());
encounterHistory.setLastOPDDate(patientDemographics.getLastOPDDate());

encounterHistory.setLastOPDFreeCount(patientDemographics.getLastOPDFreeCount());
encounterHistory.setLastNotesID(null);
encounterHistory.setLastIPDDate(null);
encounterHistory.setLastIPDFreeCount(patientDemographics.getLastIPDFreeCount());
mednetDAO.saveOrUpdate(encounterHistory);
 }

1 个答案:

答案 0 :(得分:0)

在默认配置中,Spring Framework的事务基础结构代码仅在运行时未经检查的异常情况下标记用于回滚的事务;也就是说,抛出的异常是RuntimeException的实例或子类。从事务方法抛出的已检查异常不会导致默认情况下的回滚 配置。

从方法签名中删除throws并抛出RuntimeException

if(count == 1){
   throw new RuntimeException(count+" Records Saved");
}