What is the best way to handle a ConstraintViolationException exception with EJB3 and entitymanager in an SLSB

advertisements

here is my code snippet:

@Stateless
public class mySLSB {

@PersistenceContext(unitName = "db")
private EntityManager myEntityManager;

 public void crud(MyEntity myEntity) throws MyException {
  myEntityManager.merge(myEntity);
 }
}

However this merge can cause a ConstraintViolationException, which does not throw MyException (which is caught in the calling servlet).

What is the best way to catch hibernate exceptions ?


However this merge can cause a ConstraintViolationException, which does not throw MyException (which is caught in the calling servlet). What is the best way to catch hibernate exceptions?

When using JPA and the EntityManager API, you'll get a javax.persistence.RollbackException with the ConstraintViolationException as cause. So catch the RollbackException and use getCause() to inspect it.