【问题标题】:removing entity from database that has already been removed从已删除的数据库中删除实体
【发布时间】:2015-09-11 17:16:57
【问题描述】:

在我的应用程序中,客户端有一个持久化实体的副本,存储在一个集合中,以便最大限度地减少数据库事务。由于它是一个多用户系统,另一个用户可能正在查看同一个对象,比如与您一起查看任务实体。假设第二个用户在您查看任务时从数据库中删除了该任务,并且您决定也将其删除。当您尝试删除它时,我收到 StackOverflowError,当然不会执行删除(因为任务已被删除)。有没有办法使用数据库、jpa 或休眠异常来捕获这个?我正在使用 entitymanager obects 来删除实体。

public <T> void remove(T entity) throws PersistenceException{
    log.debug("Removing entity of type " + entity.getClass().getName());

    // TODO add exception handling
    EntityManager em = createEntityManager();
    em.getTransaction().begin();
    em.remove(em.merge(entity));
    em.getTransaction().commit();
    em.close();
}

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    如果您正在寻找捕获异常;那么你可以尝试如下--

    public <T> void remove(T entity) throws PersistenceException{
    log.debug("Removing entity of type " + entity.getClass().getName());
     EntityManager em =null;
     EntityTransaction et=null;
    try{
          em = createEntityManager();
          et=em.getTransaction();
       if(!et.isActive()){  // you should have new txn always. else throw expception
         et.begin();
          ....  // your remove logic
        et.commit();
        em.close();
        } else{
           et.setRollbackOnly();
            throw new RunTimeException(..); //optional throw
        }
     }catch(Exception e) {
       et.rollback();
       throw new RunTimeException(...)..; //optional throw
    }
    

    【讨论】:

      【解决方案2】:

      这里有一个乐观锁定问题。不仅移除会很麻烦。可能有两个或更多人编辑同一个实体(或者一个人会编辑一个实体,另一个人会删除它,最终结果应该是什么?)。

      在您的情况下,在删除实体之前,您需要先将其加载到您的事务中。如果未找到,则有人已将其删除。否则,您可以安全地删除它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多