如何制作cascade =“all,delete-orphan”的hibernate集合副本 [英] How to make a copy of hibernate collection with cascade="all,delete-orphan"
问题描述
A a =(A)会话。 get(A.class,id);
session.evict(a);
a.setId(null);
session.save(a);
然而,这并不奏效,我得到以下期待:
org.hibernate.HibernateException:不要更改cascade =all-delete-orphan集合的引用:com.test.AB
它可以安全地承担这个错误,因为我有一个在实体A中定义的B实体的集合:
< list name =Btable =Blazy =falsecascade =all,delete-orphan>
< key column =A_IDnot-null =true/>
< index column =X/>
< / list>
如何制作实体A的副本,包括实体B的集合而不休眠不满意?
以前在我的项目中遇到同样的问题。
对我来说,它的工作原理是将list-entries的ID设置为null。
//通过使用序列化复制一个aOriginal clone
a.setId(null);
for(B b:a.getBs()){
b.setId(null);
}
session.save(a);
对于克隆本身,我使用 Apache SerializationUtils clone 。
原因是,hibernate试图复用已经存在的复制实体的列表条目。但是这个已经存在的列表条目被链接到一个原始实体。所以它试图在实体中改变列表本身,因为实体改变了。但是,如果用删除孤儿(只能修改列表中的条目,而不是列表本身)注释,则不能更改列表。所以引发异常。
如果我将list-entry-id设置为null,它们也会被插入newley。对象层次结构(而不是仅主要实体)被复制。所以豁免不再被抛出。
I am trying to make a copy of a hibernate entity A like this:
A a = (A) session.get(A.class, id);
session.evict(a);
a.setId(null);
session.save(a);
This however does not work and i get the following expetion:
org.hibernate.HibernateException: Don't change the reference to a collection with cascade="all-delete-orphan": com.test.A.B
Its safe to assume this error happens because of i have a collection of B entity defined in entity A:
<list name="B" table="B" lazy="false" cascade="all,delete-orphan">
<key column="A_ID" not-null="true"/>
<index column="X"/>
<one-to-many class="com.test.B"/>
</list>
How is it possible to make a copy of entity A, including its collection of entitys B without hibernate being unhappy about it?
I had the same problem previously in my project.
For me it works, to set the ID of the list-entries to null.
// make copy a of aOriginal by using serialisation clone
a.setId(null);
for (B b : a.getBs()) {
b.setId(null);
}
session.save(a);
For the clone itself I used the Apache SerializationUtils clone.
The reason is, that hibernate tries to "reuse" already persisted list-entries for the "copied" entity. But this already persisted list-entries are linked to a original entity. So it tries to "change" the list itself in the entity, because the entity changed. But you can't change the list if it is annotated with "delete-orphans" (you only can modify the entries of the list, but not the list itself). So the exception is thrown.
If I set the list-entry-IDs to null, they will also be inserted newley. And the object hierarchy (instead of only the main entity) is duplicated. So the exeption is no longer thrown.
这篇关于如何制作cascade =“all,delete-orphan”的hibernate集合副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!