使用JPA在C​​onstraintViolationException之后保持持久化/合并

时间:2017-01-17 18:37:53

标签: java hibernate jpa persist open-session-in-view

如何在View策略中使用JPA + Hibernate和Open Session在ConstraintViolationException之后合并和更新实体?

userTransaction.begin();

try {
    em.persist(entity);
} catch (PersistenceException ce){
    ConstraintViolationException t = (ConstraintViolationException) ce.getCause();
    String constraint = t.getConstraintName();
    if (constraint.equals(ConstantesUtil.MY_UK_CONFIG) == false ){
        throw new Exception(ce);
    } else {
        entity = findByUk(entity);
    }
} catch (Exception e){
    throw new Exception(e);
}

entity.setOtherPropertyValue('forExample');

em.merge(entity);

userTransaction.commit();

我知道在异常之后,事务/会话变脏了。有没有办法清理它并坚持合并?

0 个答案:

没有答案