【发布时间】:2009-07-09 21:49:40
【问题描述】:
我想在 JPA 中制作实体的深层副本。我在这里发现了一个有趣的讨论: http://forums.java.net/jive/thread.jspa?messageID=253092&tstart=0
听起来提议的解决方案是将所有@Id 设置为零。这是我的基本代码:
//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 代码???
谢谢!
【问题讨论】:
-
链接已损坏。你能更新一下吗?
-
您确定要进行深层复制吗?这可能导致整个数据库重复。我宁愿坚持实施复制 - 乏味,但可以让我头疼或更糟,服务器在生产中崩溃。