Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top