hibernate問題——a different object with the same identifier value

 最近在項目中使用Hibernate時出現a different object with the same identifier value was already associated with the session。當時是A 對象內包含B和C對象,C對象中也包含B對象,session同時取出A對象和C對象,之後修改A對象之後session.update(A)出現 a different object with the same identifier value was already associated with the session的問題。在網上查了一下沒有更好的解決方案,下面是找到的比較好的解決方法:

http://myreligion.iteye.com/blog/371103 寫道
a different object with the same identifier value was already associated with the session。

  錯誤原因:在hibernate中同一個session裏面有了兩個相同標識但是是不同實體。

  解決方法一:session.clean()

  PS:如果在clean操作後面又進行了saveOrUpdate(object)等改變數據狀態的操作,有可能會報出"Found two representations of same collection"異常。

  解決方法二:session.refresh(object)

  PS:當object不是數據庫中已有數據的對象的時候,不能使用session.refresh(object)因爲該方法是從hibernate的 session中去重新取object,如果session中沒有這個對象,則會報錯所以當你使用saveOrUpdate(object)之前還需要判斷一下。

  解決方法三:session.merge(object)

  PS:Hibernate裏面自帶的方法,推薦使用。

 同時可以參照http://opensource.atlassian.com/projects/hibernate/browse/HHH-509中的內容,可以找到很多有參照價值的內容。

個人在解決問題的時候使用了session.merge(object),可以順利解決問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章