2013-02-25 95 views
2


我想刪除數據庫中不存在的實體,但delete()方法不會發出任何異常。
當我嘗試刪除不存在的實體時,如何得到錯誤?
我抄我下面的代碼:什麼時候org.hibernate.Session拋出HibernateException?

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()何時會拋出異常。

回答

1

我認爲您發現的問題與您嘗試刪除的對象的狀態有關。有3個主要狀態由hibernate使用:瞬態,持久性和分離。

一個瞬時實例是一個從未被持久化過的全新實例。一旦你堅持下去,它就會持久。連接關閉並且對象已被保留後,它將被分離。該文檔詳細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時,hibernate會忽略它。刪除表示它從數據存儲中刪除持久實例。 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); 
    } 
} 
相關問題