简体   繁体   中英

Spring annotation transaction rollback done not working for two tables

I'm facing one problem, if there are two insert statement and there is exception in second insert query, rollback is not working properly.

Insert 1 for table PatientDemographics SUCCESS
Insert 2 for table EncounterHistory FAILS

Then result of insert 1 should not rollback (not revert from database automatically, it is to insert a record in the database).

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

In its default configuration, the Spring Framework's transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException . Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.

Remove throws from your method signature and throw RuntimeException :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM