JPA中的深层复制 [英] Deep Copy in JPA

查看:204
本文介绍了JPA中的深层复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JPA中复制实体的深层副本.我在这里找到了一个有趣的讨论: http://forums.java.net/jive/thread.jspa ?messageID = 253092& tstart = 0

I would like to make a deep copy of an entity in JPA. I found an interesting discussion here: http://forums.java.net/jive/thread.jspa?messageID=253092&tstart=0

听起来,建议的解决方案是将所有@Id设置为零.这是我的基本代码:

It sounded like the proposed solution was to set all @Id's to zero. Here's my basic code:


//Start a JPA session.
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();

//Get the object I want to copy.
MyClass myObject=em.find(MyClass.class,id);

//Use reflection to find @Id's and set them to zero for all @OneToMany and @OneToOne relations.
//TODO:  write the ugly recursive code to do this.

//Hoping this will create a deep copy.
em.merge(myObject);

//Close the session.
em.getTransaction().commit();
em.close();

这是一个好策略吗?可能有人已经编写了此TODO代码以供他们共享吗?

Is this a good strategy? Might anyone have this TODO code already written that they can share???

谢谢!

推荐答案

我能够按照问题中的描述获取深层副本.迫切需要加载整个图形并将@Id重置为null或零.我发现Hibernate SessionFactory实际上具有帮助此过程的方法.

I was able to get a deep copy to work as described in the question. It is necessary to eagerly load the whole graph and reset the @Id's to null or zero. I found that the Hibernate SessionFactory actually has methods to help with this process.

上面关于深层副本的其他建议似乎没有用.当然,问题可能出在键盘和椅子之间.但是它现在正在工作.

The other recommendations above for deep copies didn't seem to work. Granted, the problem may have been between keyboard and chair. But it's working now.

谢谢大家!

这篇关于JPA中的深层复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆