简体   繁体   English

Spring Data Jpa - 如何进行回滚?

[英]Spring Data Jpa - How to perform roll back?

How to perform rollback in Spring Data JPA for the following scenario? 如何在Spring Data JPA中执行以下场景的回滚?

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? 如果第22行失败,如何回退第11行?

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. 1)如果ResponseStatusExceptionInternalServerException都是RuntimeExceptions那么你不需要做任何事情,因为默认情况下Spring会回滚任何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. 2)请记住,在事务提交之前,在entityManager上调用save()和最终persist()不会导致DB上的任何物理更新。 These methods simply register an entity in the Persistence Context. 这些方法只是在持久化上下文中注册实体。

Use "rollbackFor" 使用“rollbackFor”

@Transactional(rollbackFor = DataIntegrityViolationException.class)

Multiple exception: 多个例外:

@Transactional(rollbackFor = { ResponseStatusException.class, InternalServerException.class })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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