Reputation: 22369
Given an entity B which has a String and a Date value.
An instance of B is created once per workload and is shared by all other entities created in a per work load.
B bee = new B();
We have another entity class A which we create only once per workload, and have:
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
List<B> bees = new B();
We then add a.bees.add(bee);
once for entity a and once for other entity types, c - z.
Now, since this bee is shared, what happens when I delete an entity of type A that has this b ?
Will hibernate attempt to delete B despite it being potentially referenced by other entities other than A?
Is there a way to ORPHANDELETE / CASCADE DELETE only when the b is no longer referenced ANYWHERE?
Upvotes: 1
Views: 1120
Reputation: 8213
orphanRemoval
or CascadeType.REMOVE
are used to delete the child entity, when child entity is no longer referenced by parent entity or when the parent entity is deleted. In both scenarios, you are operating on the retrieved parent entity, so hibernate will take the action on child entity because it already knows.
To achieve your goal, hibernate need to know who else have reference to that child entity. There is no way hibernate can do it automatically.
But if your child entity has reference to the all other entities, you can make it no longer reference those other entities, so only the parent entity will be left as the one associated with it. So now when you remove it from this parent, it can be deleted via orphanRemoval
or CascadeType.REMOVE
Upvotes: 3