将对象与 FetchType.EAGER 关系合并会导致“FailedObject”。
我有一个实体 VM 与另一个实体 BP 存在关系。这种关系是急切的。首先我加载一个虚拟机。加载后,VM 在客户端分离、序列化和更改。现在我想更新更改后的实体,因此我使用 JPA 中的 EntityManager.merge() 方法。现在我在 OpenJPA 中遇到以下错误:
“附加期间在持久字段“Vm.bp”中遇到新对象。但是,该字段不允许级联附加。将此字段的级联属性设置为 CascadeType.MERGE 或 CascadeType.ALL(JPA 注释)或“合并”或“全部”(JPA orm.xml),您无法在不层叠的情况下附加对新对象的引用。”
为什么我必须将 Cascade.MERGE 添加到与另一个永远不会改变的实体的关系中?为什么 JPA 认为 BP 是一个新对象(“...无法附加对新对象的引用...”)? 使用 ManyToOne 关系时,我是否始终必须添加 Cascade.MERGE 才能更新实体,还是因为 EAGER 获取类型所致?
这是我的实体:
@Entity
@Table(name = "VM")
public class Vm extends BaseEntity implements Serializable {
public static final long serialVersionUID = -8495541781540291902L;
@Id
@SequenceGenerator(name = "SeqVm", sequenceName = "SEQ_VM")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqVm")
@Column(name = "ID")
private Long id;
// lots of other fields and relations
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BP_ID")
private Bp bp;
// ...
}
I have an entity VM with a relationship to another entity BP. The relationship is eagerly fetched. First I load a VM. After loading the VM is detached, serialized and changed at the client side. Now I want to update the changed entity so I use the EntityManager.merge() method from JPA. Now I run into the following error from OpenJPA:
"Encountered new object in persistent field "Vm.bp" during attach. However, this field does not allow cascade attach. Set the cascade attribute for this field to CascadeType.MERGE or CascadeType.ALL (JPA annotations) or "merge" or "all" (JPA orm.xml). You cannot attach a reference to a new object without cascading."
Why do I have to add a Cascade.MERGE to a relationship to another entity that will never change? And why does JPA think that BP is a new object ("...cannot attach reference to a new object...")?
When using ManyToOne relationships do I always have to add Cascade.MERGE in order to update the entity or is this because of the EAGER fetch type?
Here's my entity:
@Entity
@Table(name = "VM")
public class Vm extends BaseEntity implements Serializable {
public static final long serialVersionUID = -8495541781540291902L;
@Id
@SequenceGenerator(name = "SeqVm", sequenceName = "SEQ_VM")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqVm")
@Column(name = "ID")
private Long id;
// lots of other fields and relations
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BP_ID")
private Bp bp;
// ...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了出现此错误消息的原因:相关Bp实体的@Version注释的数据库字段初始化为“0”。显然 OpenJPA (1.2.3) 无法处理零实体版本。
将版本设置为 1 解决了我的问题。
I found the reason why this error message comes up: The @Version annotated database field of the related Bp entity was initialized with "0". Apparently OpenJPA (1.2.3) is not able to cope with entity versions of zero.
Setting the version to 1 solved my issue.