JPA:如何防止级联操作[持久化、删除...]?

3

我有两个实体

@Entity
@Table(name="parent")
public class Parent {
  @Id
  String uuid;

  @ElementCollection(fetch=FetchType.EAGER)
  @CollectionTable(
      name="child",
      joinColumns=@JoinColumn(name="parent_uuid", insertable=false, updatable=false)
  )

  @Column(name="uuid")
  private Set<String> childrenUuids = new HashSet<String>();
}

@Entity
@Table(name="child") 
public class Child {
  @Id
  String uuid;

  @Column(name="parent_uuid")
  String parentUuid;

}

现在,当我持久化 Parent 对象时,由于 ManyToOne 关系,childrenUuids 中的子对象也会自动持久化。我想阻止所有对 Parent 对象的操作(例如持久化,删除...)被级联到 Child 对象,这在 JPA 中是否可行?我已经研究了几天,但没有找到答案。谢谢。

2个回答

1
你应该使用@OneToMany而不是@ElementCollection。默认情况下,@OneToMany不会级联。据我所知,@ElementCollection始终会级联,这在某种程度上是有道理的,因为“@ElementCollection定义了一个基本类型或可嵌入类实例的集合”,而基本类型/可嵌入类被认为是其父类的组成部分。

谢谢。问题是我的Child对象在实际情况下相当大,实际上我只需要其中的一列。加载整个Child对象对我来说成本太高了。有没有办法在不使用级联的情况下实现CollectionTable的相同效果? - zx_wing
显然@OneToMany是用于关系的,而Set<String>不是一个关系,所以你不应该使用它。 - DataNucleus

0

@ElementCollection 总是级联的。我最终通过实现 @ElementCollection 的解决方案来解决这个问题。我仍然使用 JPA 注释,但是我在 @ElementCollection 上面添加了 @Transient,以使 JPA 忽略它。然后我将我的实现作为 JPA post-load 监听器放置到每个实体中,这将在实体加载后填充每个集合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接