1

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?

mjs
  • 21,431
  • 31
  • 118
  • 200
  • [This](https://stackoverflow.com/questions/29697183/make-2-different-parent-entities-reference-a-child-entity-through-onetomany-in) question is similar, but it doesn't really say whether the child-entity is only deleted once orphaned by all parents or just either parent. You could create a simple unit test and try it out for yourself, I guess. – Erik Karlstrand Aug 12 '20 at 19:38
  • Yes, i've come across similar but not quite this case. – mjs Aug 12 '20 at 20:19

1 Answers1

3
  • 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