我正在尝试像这样制作一个 hibernate 实体 A 的副本:
A a = (A) session.get(A.class, id);
session.evict(a);
a.setId(null);
session.save(a);
但是这不起作用,我得到以下实验:
org.hibernate.HibernateException: Don't change the reference to a collection with cascade="all-delete-orphan": com.test.A.B
可以安全地假设发生此错误是因为我在实体 A 中定义了 B 实体的集合:
<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>
如何制作实体 A 的副本,包括它的实体 B 的集合,而 hibernate 对此不满意?
最佳答案
如果你想复制一个现有的实体——修改它——并将它保存为新实体,那么你需要深复制那个对象。您可以通过序列化然后反序列化该对象来深拷贝对象。
public Object deepCopy(Object input) {
Object output = null;
try {
// Writes the object
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(input);
// Reads the object
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
output = objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
关于java - 如何使用级联 ="all,delete-orphan"制作 hibernate 集合的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42952330/