如何在Spring中为下列场景执行回滚?
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;
}如果第22行失败,如何回滚-11行?
发布于 2019-08-05 12:21:02
1),如果ResponseStatusException和InternalServerException都是RuntimeExceptions,那么您就不需要做任何事情了,因为在默认情况下,Spring会在任何RTE上回滚整个事务。
2)只需记住,在事务提交之前,调用save()并最终在entityManager上调用persist()不会导致DB上的任何物理更新。这些方法只需在持久性上下文中注册一个实体。
发布于 2019-08-05 12:23:52
使用"rollbackFor"
@Transactional(rollbackFor = DataIntegrityViolationException.class)多重例外:
@Transactional(rollbackFor = { ResponseStatusException.class, InternalServerException.class })https://stackoverflow.com/questions/57358334
复制相似问题