Issue
how can I discard changes after Exception? I want to save recordB even when recordA failed to save.
//The transaction comes from else where, cannot modify it
@Transactional
void updateRecord{
Record recordA = repository.findById(ida);
Record recordB = repository.findById(idb);
recordA.setXXX();
recordB.setXXX();
try {
repository.saveAndFlush(recordA);
} catch (Exception exp) {
if (exp instanceof DataIntegrityViolationException) {
entityManager.detach(recordA);
} else {
throw new RuntimeException(exp);
}
}
repository.saveAndFlush(recordB);//got exception cause recordA still engaged
}
Solution
Can not be done in same transaction.
1: need to set globalRollbackOnParticipationFailure = true
2: start an new transaction with proper propagation, do everything and rollback within that transaction
Answered By - Rockman12352
Answer Checked By - David Goodson (JavaFixing Volunteer)