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?