如何克隆JPA实体 [英] How to clone a JPA entity
本文介绍了如何克隆JPA实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在数据库中保留了一个JPA实体.
我想拥有一个副本(具有不同的ID),并修改了某些字段.
I have a JPA entity already persisted in the database.
I would like to have a copy of it (with a different id), with some fields modified.
最简单的方法是什么?喜欢:
What is the easiest way to do this? Like:
- 将它的
@Id
字段设置为null
并保留它会起作用吗? - 我是否需要为实体创建一个克隆方法(复制除
@Id
以外的所有字段)? - 还有其他方法(例如使用克隆框架)吗?
- setting it's
@Id
field tonull
and persisting it will work? - will I have to create a clone method for the entity (copying all fields except the
@Id
)? - is there any other approach (like using a cloning framework)?
推荐答案
使用EntityManager.detach
.它使bean不再链接到EntityManager.然后将ID设置为新ID(如果为自动,则为null),更改所需字段并保留.
Use EntityManager.detach
. It makes the bean no longer linked to the EntityManager. Then set the Id to the new Id (or null if automatic), change the fields that you need and persist.
这篇关于如何克隆JPA实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文