如何克隆 JPA 实体 [英] How to clone a JPA entity

查看:46
本文介绍了如何克隆 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 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天全站免登陆