Hibernate在共享实体上的orphanRemoval功能

huangapple go评论67阅读模式
英文:

Hibernate orphanRemoval on shared entities

问题

给定一个实体 B,它有一个字符串和一个日期值。

在每个工作负载中只创建一个 B 的实例,然后由所有其他实体共享。

B bee = new B();

我们有另一个实体类 A,我们每个工作负载只创建一次,并且有:

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
List<B> bees = new ArrayList<B>();

然后,我们为实体 a 添加 a.bees.add(bee); 一次,其他实体类型 c - z 也是一样。

现在,由于这个 bee 是共享的,当我删除一个类型为 A 的实体,它有这个 b 的引用时会发生什么?

Hibernate 会尝试删除 B,尽管它可能被除 A 以外的其他实体引用吗?

是否有一种方法可以在 b 不再被任何地方引用时才进行 ORPHANDELETE / CASCADE DELETE?

英文:

Given an entity B which has a String and a Date value.

An instance of B is created once per workload and is shared by all other entities created in a per work load.

 B bee = new B();

We have another entity class A which we create only once per workload, and have:

  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
  List&lt;B&gt; bees = new B(); 

We then add a.bees.add(bee); once for entity a and once for other entity types, c - z.

Now, since this bee is shared, what happens when I delete an entity of type A that has this b ?

Will hibernate attempt to delete B despite it being potentially referenced by other entities other than A?

Is there a way to ORPHANDELETE / CASCADE DELETE only when the b is no longer referenced ANYWHERE?

答案1

得分: 3

  • orphanRemovalCascadeType.REMOVE 用于在子实体不再由父实体引用或父实体被删除时删除子实体。在这两种情况下,您操作的是检索到的父实体,因此 Hibernate 将对子实体采取操作,因为它已经知道。

  • 要实现您的目标,Hibernate 需要知道还有谁引用了该子实体。Hibernate 无法自动完成这项任务。

  • 但如果您的子实体引用了所有其他实体,您可以使其不再引用这些其他实体,因此只有父实体将与其关联。因此,现在当您从此父实体中删除它时,可以通过 orphanRemovalCascadeType.REMOVE 删除它。

英文:
  • orphanRemoval or CascadeType.REMOVE are used to delete the child entity, when child entity is no longer referenced by parent entity or when the parent entity is deleted. In both scenarios, you are operating on the retrieved parent entity, so hibernate will take the action on child entity because it already knows.

  • To achieve your goal, hibernate need to know who else have reference to that child entity. There is no way hibernate can do it automatically.

  • But if your child entity has reference to the all other entities, you can make it no longer reference those other entities, so only the parent entity will be left as the one associated with it. So now when you remove it from this parent, it can be deleted via orphanRemoval or CascadeType.REMOVE

huangapple
  • 本文由 发表于 2020年8月13日 03:26:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63383483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定