Keep persist/merge after a ConstraintViolationException using JPA

501 views Asked by At

How can I merge and update an entity after a ConstraintViolationException using JPA + Hibernate and Open Session in View strategy?

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();

I know that after an exception the transaction/session becomes dirty. Does have any way to clean it and persist ou merge?

0

There are 0 answers