【问题标题】:h2 jpa delete method not working javah2 jpa删除方法不起作用java
【发布时间】:2016-10-04 03:41:50
【问题描述】:

我正在尝试测试此方法以从 h2 数据库中删除实体:

public boolean delete(T entity) {
     if (entity == null) {
        throw new IllegalArgumentException();
    }

    boolean ret = true;

    EntityManager em = entityManager();

    try {
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.remove(em.merge(entity));
        tx.commit();
    } catch (RollbackException ex) {
        ret = false;
    } finally {
        em.close();
    }

    return ret;
}

如果实体在数据库中并将其删除,则该方法返回 true,但如果给定的实体不在数据库中,它也会返回 true。有人可以解释我为什么吗?谢谢。

【问题讨论】:

  • 删除不存在的实体会导致异常吗?
  • 这就是我想要做的,但不知道它是否真的有效

标签: java database jpa h2 entitymanager


【解决方案1】:

merge 将保留一个不存在的实体。因此,您正在创建一个实体(使用merge),然后立即删除它(使用remove)。因此不会抛出异常。

如果你想删除一个实体并返回一个布尔值,无论你是否删除它,那么你可以这样做......

public boolean delete(T entity) {

    if (entity == null) {
        throw new IllegalArgumentException();
    }

    EntityManager em = entityManager();
    EntityTransaction tx = em.getTransaction();

    try {
        tx.begin();
        em.refresh(entity);
        em.remove(entity);
        tx.commit();
        return true;
    } catch (EntityNotFoundException ex) {
        tx.rollback();
        return false;
    } catch (RuntimeException ex) {
        tx.rollback();
        throw ex;
    } finally {
        em.close();
    }

}

【讨论】:

  • 那我该怎么做呢?因为我删除了合并,但它仍然是一样的
  • refresh 方法抛出 EntityNotFoundException 或者您可以通过 find 方法检查实体是否在 db 中退出。如果实体不存在,Find 将返回 null。
猜你喜欢
  • 2014-02-18
  • 2017-02-25
  • 2021-12-23
  • 2017-01-16
  • 2018-12-22
  • 2016-08-30
  • 2011-06-22
  • 1970-01-01
相关资源
最近更新 更多