simple problem. Here is the code :
public void insertDefacer(Defacer defacer) {
try {
em.persist(defacer);
} catch (PersistenceException | DatabaseException e) {
defacer = em.find(Defacer.class, defacer.getIdentity());
defacer.setStats(defacer.getStats() + 1);
em.merge(defacer);
}
}
when defacer already exists in database (mysql), the persist
operation throws an Exception ( PersistenceException
and/or DatabaseException
). It seems normal. So I want to catch these exceptions and threat them. But after logging these exceptions, my program ends abruptly (without finish the method).
Why ?
Detail (It could be important or not) : em is an EntityManager get through @PersistenceContext
Are you trying this way to get EntityManager?
@PersistenceContext
private EntityManager em;
public EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
You should not be using your EntityManager
inside the catch
clause as it may be in a corrupted state. Exceptions in JPA are not recoverable, so you should assume that your transaction cannot and will not be completed if an Exception happens.
public void insertDefacer(Defacer defacer) {
EntityTransaction tx = null;
try {
tx = em.getTransaction();
tx.begin();
em.persist(defacer);
tx.commit();
} catch (Exception ex) {
if(tx != null && tx.isActive()) tx.rollback();
} finally {
em.close();
}
}
I found an alternative. Just see the code :
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void insertDefacer(Defacer defacer) {
Defacer df = em.find(Defacer.class, defacer.getIdentity());
if(df == null) {
em.persist(defacer);
System.out.println("Save");
} else {
em.merge(defacer);
System.out.println("Update");
}
}
As I said It's a palliative solution . Thanks for your help.
确保PersistenceExcetion属于休眠包。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.