2


我正在尝试删除数据库中不存在的实体,但 delete() 方法没有任何异常。
当我尝试删除不存在的实体时,如何得到错误?
我在下面复制了我的代码:

public void remove(MyEntity persistentInstance) {
 logger.debug("removing entity: " + persistentInstance);
    try {
        sessionFactory.getCurrentSession().delete(persistentInstance);
        logger.debug("remove successful");
    } catch (final RuntimeException re) {
        logger.error("remove failed", re);
        throw re;
    }
}

编辑:
我使用以下代码在测试中调用删除:

final MyEntity instance2 = new MyEntity (Utilities.maxid + 1); //non existent id
    try {
        mydao.remove(instance2);
        sessionFactory.getCurrentSession().flush();
        fail(removeFailed);
    } catch (final RuntimeException ex) {

    }

即使我调用刷新测试也不会失败,为什么?
我想得到一个例外。无论如何,我也有兴趣了解 delete() 何时会引发异常。

4

1 回答 1

1

我认为您发现的问题与您尝试删除的对象的状态有关。hibernate 使用 3 种主要状态:瞬态、持久和分离。

瞬态实例是从未持久化的全新实例。一旦你坚持它,它就会变得持久。在连接关闭并且对象被持久化后,它被分离。文档更详细地解释了https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/objectstate.html#objectstate-overview

这是一个例子:

MyEntity foo = new MyEntity(); // foo is a transient instance
sessionFactory.getCurrentSession.persist(foo); // foo is now a persisted instance
txn.commit(); // foo is now a detatched instance

在您的示例中,您正在创建一个具有未使用 id 的全新实例,您的实例是瞬态的(从未被持久化)。我认为当您为瞬态实例调用 delete 时,休眠会忽略。Delete 表示它从数据存储中删除了一个持久实例。https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#delete(java.lang.Object)

相反,尝试这样的事情:

public void remove(long entityId) {
    MyEntity myEntity = myEntityDAO.findById(entityId);
    if (myEntity == null) {
        // error logic here
    } else {
        sessionFactory.getCurrentSession().delete(myEntity);
    }
}
于 2014-07-16T19:17:11.487 回答