首页 > 解决方案 > 发生异常后如何丢弃hibernate/JPA中的更改?

问题描述

异常后如何丢弃更改?即使recordA保存失败,我也想保存recordB。

//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
}

标签: javahibernatejpaspring-data-jpa

解决方案


不能在同一事务中完成。

1:需要设置 globalRollbackOnParticipationFailure = true

2:通过适当的传播开始一个新事务,在该事务中做所有事情并回滚


推荐阅读