克隆JPA实体 [英] Cloning JPA entity

查看:88
本文介绍了克隆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 <之外的所有字段/ code>)?

  • 有没有其他方法(比如使用克隆框架)?

  • setting it's @Id field to null 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屋!

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