如何在休眠中的多对一映射上定义反向级联删除 [英] how to define an inverse cascade delete on a many-to-one mapping in hibernate
问题描述
我有两个类 A 和 B.许多 B 可以与单个 A 关联,因此从 B 到 A 是多对一的关系.我已经映射了这种关系:
I have two classes A and B. Many B's can have association with a single A, hence a many-to-one relationship from B to A. I've mapped the relationship like:
<class name="A" table="tbl_A">
<property name="propA" column="colA"/>
</class>
<class name="B" table="tbl_B">
<property name="propB" column="colB"/>
<many-to-one name="a" class="A" column="col1" cascade="delete"/>
</class>
A 没有任何映射到 B.记住这一点,我们打算在 B 关联 A 被删除时删除 B.如果我可以在 B 中的多对一关联上定义一个 inverse="true" 但休眠不允许这样做,这本来是可能的.
A has nothing mapped to B. Keeping this in mind we intend to delete B when it's associated A is deleted. This could have been possible if I could define an inverse="true" on the many-to-one association in B but hibernate does not allow that.
有人可以帮忙吗?我们不想为此在 A 中写任何东西.
Can anyone help with this? We do not want to write anything in A for this.
推荐答案
Hibernate 仅沿定义的关联级联.如果 A 对 B 一无所知,那么你对 A 所做的任何事情都不会影响 B.
Hibernate only cascades along the defined associations. If A knows nothing about Bs, nothing you do with A will affect Bs.
因此,Pascal 的建议是做您想做的事情的最简单方法:
Pascal's suggestion is, therefore, the easiest way to do what you want:
<class name="A" table="tbl_A">
...
<set name="myBs" inverse="true" cascade="all,delete-orphan">
<key column="col1"/>
<one-to-many class="B"/>
</set>
</class>
<class name="B" table="tbl_B">
...
<many-to-one name="a" class="A" column="col1" not-null="true"/>
</class>
请注意,在 B
上设置 cascade="delete"
就像在原始代码中一样不会执行您想要的操作 - 它告诉 Hibernate如果B 被删除",这可能会导致违反约束(如果有任何其他 B 链接到该 A).
Note that setting cascade="delete"
on B
as you have it in your original code will NOT do what you want - it tells Hibernate to "delete A if B is deleted" which is likely to result in constraint violation (if there are any other Bs linked to that A).
如果您绝对不能将 B 的集合添加到 A(尽管我无法真正想到会出现这种情况的情况),那么您唯一的另一种选择是在外部定义从 A 到 B 的级联删除关键级别;当你的 A 被删除时,你的 B 也会被删除.
If you absolutely cannot add a collection of Bs to A (though I can't really think of the circumstances where that'd be the case), your only other alternative is to define cascade delete from A to B at the foreign key level; your Bs will then be deleted when your A is deleted.
然而,这是一个相当丑陋的解决方案,因为您必须非常小心在 Hibernate 中删除 A 的方式:
This is a rather ugly solution, however, because you have to be extremely careful of how you delete A in Hibernate:
- 在删除 A 之前必须刷新会话(对 B 进行挂起的更新可能会导致错误或 A 和一些 B 在幕后重新插入)
- 必须从所有活动会话和二级缓存中逐出所有链接到您的 A 的 B(并且由于您没有维护 A 端的关系,这意味着所有 B)必须被逐出.
- Session must be flushed prior to deleting A (having pending updates to B may result in an error or A and some Bs being re-inserted behind the scenes)
- All Bs linked to your A (and since you're not maintaining the relationship from A side that means all Bs) must be evicted from all active sessions and 2nd level cache.
这篇关于如何在休眠中的多对一映射上定义反向级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!