Java、Hibernate、CascadeTypes 和“垃圾收集”;孤儿

发布于 2024-12-19 03:03:03 字数 662 浏览 0 评论 0原文

我可以使用哪种级联类型,以及在哪里,让 Hibernate 在不再有“事物”引用它时自动删除该图像? (基本上是 Hibernate 中的垃圾收集)

数据库:事物表 - 图像表,是多对一的,所以很多事物可以引用同一个图像。

实体:事物、图像

它是多对一的,例如 5 个事物与一个图像有关系。

现在,我这样做:

public void delete(Thing thing)
{
    if (countReferences(thing.getImage()) > 1)
    {
        thing.setImage(null);
    }
    getSession().delete(thing);
}

如果我不执行 countReferences 操作,并且关系上存在 CascaseType.REMOVE,Hibernate 也会尝试删除 Image。当图像仍然在某处被引用时,数据库中的约束就会触发,从而导致异常。

那么,简而言之,当引用它的最后一个事物被删除时,我如何告诉 hibernate 删除该图像?

是一个

org.hibernate.event.PreDeleteEventListener

也许是一个解决方案?

What kind of cascade type can I use, and where, to have Hibernate automatically remove the Image when there are no more "Things" referring to it? (so sort of Garbagecollecting in Hibernate, basically)

Database: Thing table - Image table, is a many to one, so many Things can refer to the same image.

Entities: Thing, Image

It is many to one, so for example 5 things have a relation to the one image.

Right now, I do:

public void delete(Thing thing)
{
    if (countReferences(thing.getImage()) > 1)
    {
        thing.setImage(null);
    }
    getSession().delete(thing);
}

If I don't do the countReferences thing, and there's a CascaseType.REMOVE on the relationship, Hibernate tries to remove the Image as well. The constraint in the database fires when image is still referred to somewhere, causing an Exception.

So, in short, how can I tell hibernate to remove the Image when the last Thing referring to it is deleted?

Is a

org.hibernate.event.PreDeleteEventListener

perhaps a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失退 2024-12-26 03:03:03

在深入研究 Hibernate Docs 后,似乎不支持这样的功能。虽然我想我明白为什么不支持它。

一对多引用中,集合中的实体被视为由包含该集合的实体拥有(请参阅24.1. 关于集合的说明)。

与此相反,多对一引用没有这样的含义。被引用的实体有理由不属于引用实体。因此,即使删除了对 Image 的所有引用,也没有理由认为 Image 也应该被删除。 Image 是一个完全独立的一类实体。

因此,就您而言,似乎无法避免应用强制删除。

After digging into Hibernate Docs, it seems such a feature isn't supported. Though I think I understand why it isn't supported.

In a one-to-many reference, the entities in the collection are considered to be owned by the entity containing the collection (see 24.1. A note about collections).

As oppose to that, a many-to-one reference has no such implications. The referenced entity is, justifiably, not owned by the referring entity. So, even when all references to Image are removed, there's no reason to think that Image should also be removed. Image is a totally independent 1st class entity.

So, in your case, it seems there's no escape from applicatively forcing the delete.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文