我正在尝试测试此方法以从 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。有人可以解释一下为什么吗?谢谢。
最佳答案
merge
将保留一个实体(如果它尚不存在)。因此,您正在创建一个实体(使用merge
),然后立即删除它(使用remove
)。因此不会抛出异常。
如果你想删除一个实体并返回一个 boolean 值,无论你是否删除它,那么你可以这样做......
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();
}
}
关于java - h2 jpa删除方法不工作java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625118/