Java, Hibernate, CascadeTypes, and Orphans' Garbage Collection

What is the type of cascading type that I can use, and where so that Hibernate automatically deletes the image when there are no more "Things" referencing it? (like Garbagecollecting in Hibernate, basically)

Database: Thing table - a table of images, a lot for one, so many things can refer to the same image.

Entities: Thing, Image

This is a lot, so, for example, 5 things are related to one image.

Now I am doing:

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

If I do not execute the countReferences function, and there is CascaseType.REMOVE regarding relations, Hibernate also tries to delete the image. A database restriction is triggered when the image is still mentioned somewhere, causing an exception.

So, in short, how can I say that hibernate deletes the image, when the last Thing refers to it, is deleted?

Is an

org.hibernate.event.PreDeleteEventListener

maybe a solution?

+4
source share
1 answer

After switching to Hibernate Docs, it seems that such a function is not supported. Although I think I understand why it is not supported.

In the one-to-many directory, entities in the collection are considered to belong to the entity containing the collection (see 24.1. Collection Note ).

How to counter this, the many-to-one link has no such consequences. A linked object, by right, does not belong to a reference object. Thus, even if all links to Image removed, there is no reason to think that Image should also be deleted. Image is a fully independent first class object.

So, in your case, there seems to be no way to undo a forced delete.

+3
source

Source: https://habr.com/ru/post/1384082/


All Articles