简体   繁体   English

尝试捕获持久异常

[英]try to catch persist exception

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 ). 当数据库(mysql)中已经存在defacer时, persist操作将引发异常( PersistenceException和/或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 详细信息(可能不重要): em是通过@PersistenceContext获取的EntityManager

Are you trying this way to get EntityManager? 您是否正在尝试以这种方式获取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. 您不应在catch子句中使用EntityManager ,因为它可能处于损坏状态。 Exceptions in JPA are not recoverable, so you should assume that your transaction cannot and will not be completed if an Exception happens. JPA中的异常是不可恢复的,因此,您应该假定,如果发生异常,则您的事务无法且不会完成。

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属于休眠包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM