我想知道如何创建具有所有关联的持久对象的深层副本。 假设我有以下模型。
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;
}
我有一个场景,其中用户可能想要从一个人那里获取特定文档的副本并使文档成为他/她的文档,然后他/她可以更改其内容和名称。 在这种情况下,我可以想出一种方法来实现那种创建该文档的深层副本的场景(及其关联)。
或许如果有人知道在没有做大量数据的情况下做任何其他可能的方法来做这样的事情,因为我知道它可能对应用程序性能有害。
我还想到可能正在创建对原始文档的引用,例如具有属性originalDocument
,但这样我就无法知道哪个属性(或者可能是关联)已被更改
答案 0 :(得分:7)
执行深层复制:
public static <T> T clone(Class<T> clazz, T dtls) {
T clonedObject = (T) SerializationHelper.clone((Serializable) dtls);
return clonedObject;
}
此实用程序方法将提供实体的深层副本,您可以执行想要对克隆对象执行的操作。
答案 1 :(得分:1)
用于休眠的Jackon序列化配置:
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);
接下来
clone = getMapperInstance().readValue(getMapperInstance().writeValueAsString(this));
好吧它花了一些内存和cpu ...