a different object with the same identifier value was already associated with th

解決a different object with the same identifier value was already associated with the session錯誤

Category是樹形結構,以下是實現修改功能的代碼,一開始,我用了getHibernateTemplate().update()

結果出現a different object with the same identifier value was already associated with the session

,上網查了查,使用了getSession().flush();
  getSession().clear();

之後,另外一個問題出現了:Found two representations of same collection

於是乎,繼續找辦法解決,最後發現getHibernateTemplate().merge(category);

可以徹底解決問題,然而原理到底是如何,卻是弄不明白。


//修改category
    public void updateCategory(Category category) {        
        
        //按照傳進來的category,先把原有的category讀取出來
        Category cc=(Category)getHibernateTemplate()
                    .get(Category.class, category.getId());

        //把原有的孩子拿到
        category.setChildren(cc.getChildren());

        //把原有的父親拿到
        category.setParent(cc.getParent());
        
        //保存修改
                
        getSession().flush();
        getSession().clear();
        //不要用update()方法
        getHibernateTemplate().merge(category);

    }

 

其實要解決這個問題很簡單,只需要進行session.clean()操作就可以解決了,但是你在clean操作後面又進行了saveOrUpdate(object)操作,有可能會報出"Found two representations of same collection",我找了很多資料,沒有什麼很好的解釋,其中這篇文章幫助最大http://opensource.atlassian.com/projects/hibernate/browse/HHH-509

最後通過session.refresh(object)方法就可以解決了,注意,當object不是數據庫中已有數據的對象的時候,不能使用session.refresh(object)因爲refresh是從hibernate的session中去重新取object,如果session中沒有這個對象,則會報錯所以當你使用saveOrUpdate(object)之前還需要判斷一下

當然這個問題最容易解決的辦法還是使用Hibernate裏面自帶的merge()方法。不過我始終覺得碰到問題就用這種軟件自帶的非常用方法(和saveOrUpdate(),save(),update()相比)感覺十分不爽。

後來我還發現這種錯誤經常出現在一對多映射和多對多映射,請大家在使用一對多和多對多映射的時候要小心一些

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