首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >春数据Jpa -如何执行回滚?

春数据Jpa -如何执行回滚?
EN

Stack Overflow用户
提问于 2019-08-05 12:10:20
回答 2查看 2.8K关注 0票数 3

如何在Spring中为下列场景执行回滚?

代码语言:javascript
复制
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行?

EN

回答 2

Stack Overflow用户

发布于 2019-08-05 12:21:02

1),如果ResponseStatusExceptionInternalServerException都是RuntimeExceptions,那么您就不需要做任何事情了,因为在默认情况下,Spring会在任何RTE上回滚整个事务。

2)只需记住,在事务提交之前,调用save()并最终在entityManager上调用persist()不会导致DB上的任何物理更新。这些方法只需在持久性上下文中注册一个实体。

票数 2
EN

Stack Overflow用户

发布于 2019-08-05 12:23:52

使用"rollbackFor"

代码语言:javascript
复制
@Transactional(rollbackFor = DataIntegrityViolationException.class)

多重例外:

代码语言:javascript
复制
@Transactional(rollbackFor = { ResponseStatusException.class, InternalServerException.class })
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57358334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档