java Hibernate 实体的深度克隆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17629530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deep clone of Hibernate entity
提问by verdy
I am wondering how can I create a deep copy of a persisted object with all of its association. Let say I have the following model.
我想知道如何创建持久对象的深层副本及其所有关联。假设我有以下模型。
class Document {
String title;
String content;
Person owner;
Set<Citation> citations;
}
class Person {
String name;
Set<Document> documents;
}
class Citation {
String title;
Date date;
Set<Document> documents;
}
I have a scenario in which a user might want to grab a copy of a particular document from a person and make the document his/hers then later he / she can change its content and name. In that case I can think of one way to implement that kind of scenario which is creating a deep copy of that document (with its associations).
我有一个场景,用户可能想要从某人那里获取特定文档的副本并将该文档设为他/她的,然后他/她可以更改其内容和名称。在这种情况下,我可以想出一种方法来实现那种场景,即创建该文档的深层副本(及其关联)。
Or maybe if anyone knows of any other possible way to do such thing without doing huge copy of data because I know it may be bad for the app performance.
或者如果有人知道任何其他可能的方法来做这样的事情而不做大量的数据副本,因为我知道这可能对应用程序性能不利。
I was also thinking of may be creating a reference of to the original document like having an attribute originalDocument
but that way I won't be able to know which attribute (or maybe association) has been changed.
我还考虑可能会创建对原始文档的引用,例如具有属性,originalDocument
但这样我将无法知道哪个属性(或可能关联)已更改。
回答by Jayaram
To perform a deep copy :
要执行深复制:
public static <T> T clone(Class<T> clazz, T dtls) {
T clonedObject = (T) SerializationHelper.clone((Serializable) dtls);
return clonedObject;
}
This utility method will give a deep copy of the entity, and you can perform your desired things what you want to do with the cloned object.
此实用程序方法将提供实体的深层副本,您可以执行您想要对克隆对象执行的操作。
回答by Mr_Thorynque
Hymanon serialisation configuration for hibernate :
用于休眠的 Hymanon 序列化配置:
ObjectMapper mapperInstance
Hibernate4Module module = new Hibernate4Module();
module.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, false);
mapperInstance.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapperInstance.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
mapperInstance.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapperInstance.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapperInstance.registerModule(module);
And next
接下来
clone = getMapperInstance().readValue(getMapperInstance().writeValueAsString(this));
Ok it cost some memory and cpu...
好吧,它花费了一些内存和 CPU...