How to perform rollback in Spring Data JPA for the following scenario?
Transactional
@Override
public Employee saveEmployee(EmployeeDto dto) {
// check if EmployeeId and Department Id is present
Employee employee = this.getByEmployeeId(dto);
Department department = this.getByDepartmentId(dto);
Employee employee = convertToEntity(dto, employee, department);
employee.setEmployees(Arrays.asList(employee));
department.setEmployees(Arrays.asList(employee));
try {
employee = employeeRepository.save(employee); //line-11
} catch (DataIntegrityViolationException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ConstraintViolationException", e.getCause());
} catch (Exception ex) {
throw new InternalServerException(HttpStatus.INTERNAL_SERVER_ERROR, env.getProperty(IConst.ERROR_DB_EXCEPTION), ex);
}
EmployeeEmployeeDepartment r = new EmployeeEmployeeDepartment();
r.setId(new EmployeeDepartmentPK());
r.setEmployee(employee);
r.setDepartment(department);
r.setEmployee(employee);
try {
compositeRepository.save(r); //line-22
}catch (DataIntegrityViolationException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ConstraintViolationException", e.getCause());
}
catch (Exception ex) {
throw new InternalServerException(HttpStatus.INTERNAL_SERVER_ERROR, env.getProperty(IConst.ERROR_DB_EXCEPTION), ex);
}
return employee;
}
How to roll back line-11 if line-22 fails?
1) If ResponseStatusException and InternalServerException are both RuntimeExceptions then you do not need to do anything as Spring by default rolls back the entire transaction on any RTE.
2) Just keep in mind that invoking save() and eventually persist() on entityManager does not cause any physical update on the DB until the transaction commits. These methods simply register an entity in the Persistence Context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With