Hi,
how can I recover from PersistenceException in StatefulSessionBean.
I'm using EntityManager with PersistenceContextType.EXTENDED.
It seems that after a PersistenceException I cannot use the EntityManager any longer.
But how can the user fix wrong data input?
In my sample code I simulate the following scenario:1. User creates new entity and enters wrong data.
2. User stores that entity.
2.1. I catch the ConstraintViolationException and throw an ApplicationException in the EJB. It results in transaction rollback.
3. User gets error-message and fixes data input
4. User stores fixed entity.
4.1 It does not work. The entityManager cannot be used any longer?
5. I have no idea how to solve my problem :-(
The ejb-client code:Code:
public class TestClient {
@Inject TestSFSB mySFSB;
public void testIt() {
TestEntity myEntity = new TestEntity();
myEntity.setKey("key-that-exists-in-db"); // simulates user input that will violate a unique-constraint
try {
mySFSB.store(myEntity);
} catch (ApplicationException e) {
try {
System.out.println("Hey user we have a constraint violation, please fix your data!");
myEntity.setKey("new key that does not exist in db"); //simulates fixed user input that would not violate
mySFSB.store(myEntity);
} catch (Exception e1) {
// with the fixed data it ends here with
// javax.ejb.EJBException: javax.persistence.PersistenceException:
// org.hibernate.HibernateException: proxy handle is no longer valid
e1.printStackTrace();
}
}
}
}
The ejb:Code:
@Stateful
public class TestSFSB {
@PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager em;
public TestEntity findMasterByPk(Long id) {
TestEntity myEntity = em.find(TestEntity.class, id);
return myEntity;
}
public void store(TestEntity myEntity) throws ApplicationException {
if (em.contains(myEntity)) {
em.persist(myEntity);
} else if (myEntity.getId() != null && myEntity.getId() > 0L) {
em.merge(myEntity);
} else {
em.persist(myEntity);
}
try {
em.flush();
} catch (PersistenceException e) {
Throwable cause1 = e.getCause();
if (cause1 instanceof ConstraintViolationException) {
// first time calling the method it comes here
ConstraintViolationException cve = (ConstraintViolationException) cause1;
throw new ApplicationException(cve.getErrorCode(), e);
} else {
// second time with fixed data it ends up here with
// javax.persistence.PersistenceException: org.hibernate.HibernateException: proxy handle is no longer valid?
throw e;
}
}
}
}
Thanks for your help
Günther