2009年7月24日 星期五

Hibernate : "Found shared references to a collection"

新增資料時發生錯誤 : "Found shared references to a collection".

原因:

新增的物件是由 已存在的物件複製 , 再進行 entityManager.persist.
但 EntityManage.persist 並不會更新 one-to-many or many-to-many 的 collection reference.

BeanUtils.copyProperties and PropertyUtils.copyProperties(newPO, refPO)是淺拷貝,導致 newPO 與 refPO 這兩個物件引用的Collection是同一個Collection,這在hibernate中是不允許的,參見Hibernate reference第6章的"Two entities may not share a reference to the same collection instance"。
這種問題常見於複製時。

Solution:

newP.setxxxCollection(null) 或不要用 BeanUtils.copyPropertis 而是直接set values , depends on case.
雖然在 EntityManager.persist(newPO) 之後 EntityManager.refresh(newPO) 也可以避免這個 Exception, 但是 refresh 卻在某些狀況會發生其他的 Exception ;

Reference:
http://www.blogjava.net/leekiang/archive/2008/10/31/237908.html


沒有留言:

張貼留言