如何在使用新生成的实体标识符时深度复制Hibernate实体 [英] How to deep copy a Hibernate entity while using a newly generated entity identifier
问题描述
我正在使用一个关系数据库,该数据库使用具有一些嵌套表的单列pk。
I'm using a relational DB using a single column pk with a few nested tables.
我需要向我的项目添加一个简单的归档。归档仅在应用程序达到特定状态时发生,因此我希望做的就是将现有的休眠对象复制到新实例中,在使用新ID保存新实例的同时,保持原有对象不变。
I need to add a simple archiving to my project. The archiving only happens when the application reaches a particular state, so what I was hoping to do was copy my existing hibernate object into a new instance where the new instance would be saved with a new ID while leaving the existing object intact.
我似乎无法找出如何将现有对象复制到新实例中,而无需手动设置每个新实例字段。
I can't seem to figure out how to copy the existing object into a new instance without manually having to set every single new instance field.
有人吗?知道执行此操作的简单方法吗?
Does anybody know of a simple way of doing this?
推荐答案
我也在使用Hibernate,并且得到了与您相同的要求。我所遵循的是实现 Cloneable
。下面是一个代码示例。
I am also working with Hibernate and I got the same requirement you got. What I followed was to implement Cloneable
. Below is a code example of how to do it.
class Person implements Cloneable {
private String firstName;
private String lastName;
public Object clone() {
Person obj = new Person();
obj.setFirstName(this.firstName);
obj.setLastName(this.lastName);
return obj;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
或者您可以使用基于反射的解决方案,但我不会推荐的。请访问网站以获取更多详细信息。
Or you could go to a reflection based solution but I won't recommend that. Check this website for more details.
这篇关于如何在使用新生成的实体标识符时深度复制Hibernate实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!