java Hibernate:如果子项以多对一的方式链接到父项,如何在删除父项时使 Hibernate 从子表中删除记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/360026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:05:02  来源:igfitidea点击:

Hibernate: How to make Hibernate delete records from child table when deleting parent if child is linked to parent with many-to-one?

javamysqldatabasehibernatecascade

提问by serg

Lets say I have two tables - "child" and "parent" with many-to-one relation. What I need is to delete child entries if parent record is deleted.

假设我有两个表 - 具有多对一关系的“子”和“父”。如果删除父记录,我需要删除子条目。

It is not a problem if I link child table from parent by creating one-to-many association in parent.hbm and set cascade="all-delete-orphan".

如果我通过在 parent.hbm 中创建一对多关联并设置级联 =“all-delete-orphan”来从父级链接子表,这不是问题。

The problem is I don't want one-to-many relation on the parent side, so I created many-to-one on the child side. The reason for that is child table is pretty big and I don't want to extract hundreds of records every time I use parent. So my configuration looks like this:

问题是我不想在父端建立一对多关系,所以我在子端创建了多对一。原因是子表非常大,我不想每次使用父表时都提取数百条记录。所以我的配置是这样的:

child.hbm:

孩子.hbm:

<many-to-one name="parent" class="com.example.Parent" column="parentid"/>

while parent.hbm has no associations with child.

而 parent.hbm 与孩子没有关联。

The question is: How to make Hibernate delete records from child table when deleting a parent if a child is linked to a parent with many-to-one?

问题是:如果子项以多对一的方式链接到父项,如何在删除父项时使Hibernate从子表中删除记录?

Thanks.

谢谢。

采纳答案by Dan Vinton

Couple of options:

几个选项:

  • add the one-to-many to the parent with cascading delete, but mitigate the performance loss using lazy loading.

  • use a Hibernate Interceptor(or an aspect in an AOP environment) to detect parent record deletions and delete children.

  • 使用级联删除将一对多添加到父级,但使用延迟加载减轻性能损失。

  • 使用Hibernate Interceptor(或 AOP 环境中的一个方面)来检测父记录删除并删除子记录。

Personally I would favour the first option, as it lets your data model more closely reflect the real relationships in your data.

我个人更喜欢第一个选项,因为它可以让您的数据模型更紧密地反映数据中的真实关系。

Edit:there's a third option, but it's not pleasant - use a database trigger, and flush your Hibernate cache (or use a non-caching session).

编辑:还有第三种选择,但它并不令人愉快 - 使用数据库触发器,并刷新您的 Hibernate 缓存(或使用非缓存会话)。