0

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?

Pablo Souza
  • 863
  • 2
  • 11
  • 25
  • Assuming you're using container-managed transactions, I think you'll need to call another EJB that starts a new transaction (REQUIRES_NEW). See [this answer](http://stackoverflow.com/a/9225393/201891). – DavidS Jan 17 '17 at 18:44
  • I´m not using EJB. I´m using JTA connection with the datasource configured on JBoss Application Server. It´s possible to do something like this? – Pablo Souza Jan 17 '17 at 18:58

0 Answers0