我試圖從最初從數據庫中檢索到的HTTP會話中重新附加到會話中,我通過調用session.lock(object, LockMode.None)
來完成此操作,即使鎖定不會級聯此作品也沒關係因爲它不會將更新推送到像merge
那樣的數據庫(需要鎖定才能在彈出窗口中打開詳細信息視圖,並且稍後會在主窗口中進行實際保存)。現在令我驚訝的是,我發現如果我的實體具有一對多關係,則對該集合的任何更改都將導致HibernateException
「重關聯對象具有髒集合」。Hibernate鎖定會導致髒收集異常
我該如何重新連接對象到會話而不更新數據庫或丟棄對象上的更改呢?
這裏的情況是因爲代碼
EntityA t = createAnEntityA();
Session sess = factory.openSession();
sess.beginTransaction();
sess.save(t);
sess.getTransaction().commit();
sess.close();
// t is now saved on the DB but in dettached state
// change a simple property
sess = factory.openSession();
sess.beginTransaction();
t.setPropertyB("B");
sess.lock(t, LockMode.NONE);
// t is attached again, you won't get LazyInitializationException
// by calling its properties, although you have to be careful
// because the reattachment does not cascade to children
sess.getTransaction().commit();
sess.close();
// no updates went to the DB because setPropertyB was called
// when t was still dettached
// now change a collection
EntityC c = createAnEntityC();
t.getCollectionPropertyC().add(c);
sess = factory.openSession();
sess.beginTransaction();
sess.lock(t, LockMode.NONE);
// Exception is thrown :-(
sess.getTransaction().commit();
sess.close();
是否有可能您的解決方案之間的這個問題的答案之間的某處:http://stackoverflow.com/questions/912659/what-is-the - 合適或更新會立即更改數據庫並刷新將丟失對象中的更改,我想要的是一個簡單的重新附加,所以我不想要重新附加 - 分離 - 對象 - 休眠 – 2012-03-29 13:37:43
當我打開我的詳細視圖彈出窗口時,我沒有獲得延遲加載例外 – ilcavero 2012-03-29 14:02:47