[英]how to define an inverse cascade delete on a many-to-one mapping in hibernate
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: 我有两个类A和B.许多B可以与单个A关联,因此从B到A的多对一关系。我已经映射了这样的关系:
<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 has nothing mapped to B. Keeping this in mind we intend to delete B when it's associated A is deleted. A没有任何映射到B.记住这一点,我们打算在删除关联A时删除B. 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.
如果我可以在B中的多对一关联上定义inverse =“true”,那么这可能是可能的,但是hibernate不允许这样做。
Can anyone help with this? 有人能帮忙吗? We do not want to write anything in A for this.
我们不想为此写任何东西。
Hibernate only cascades along the defined associations. Hibernate只沿着定义的关联级联。 If A knows nothing about Bs, nothing you do with A will affect Bs.
如果A对Bs一无所知,那么你对A做的任何事情都不会影响Bs。
Pascal's suggestion is, therefore, the easiest way to do what you want: 因此,Pascal的建议是做你想做的最简单的方法:
<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>
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). 请注意,设置
cascade="delete"
上B
,你必须在你原来的代码不会做你想要的东西-它告诉Hibernate这很可能导致约束违反“如果B被删除,删除A”(如果有任何与A)相关的其他Bs。
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; 如果你绝对不能将A的集合添加到A(虽然我不能真正想到那种情况),你唯一的另一种选择是在外键级别定义从A到B的级联删除; your Bs will then be deleted when your A is deleted.
删除A后,您的B将被删除。
This is a rather ugly solution, however, because you have to be extremely careful of how you delete A in Hibernate: 但是,这是一个相当丑陋的解决方案,因为您必须非常小心如何在Hibernate中删除A:
我认为你需要从A到B的cascade="all,delete-orphan"
与one-to-many
关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.