Jpa: Unidirectional Many-To-One and Cascading Delete

JPA: unidirectional many-to-one and cascading delete

Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).

You'll therefore need to do this:

  • Either, change the unidirectional @ManyToOne relationship to a bi-directional @ManyToOne, or a unidirectional @OneToMany. You can then cascade REMOVE operations so that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection.
  • Or, specify the foreign key constraint in the child table as ON DELETE CASCADE. You'll need to invoke EntityManager.clear() after calling EntityManager.remove(parent) as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.

Unidirectional @OnetoMany mapping deletes all relationships and re-adds remaining ones rather than removing the specific one

Not sure if this is due to bag semantics(because you use a List rather than Set for reviews) or just because Hibernate sometimes does so called "collection recreations". Try using a Set.

Hibernate unidirectional many-to-one and cascading delete

You can use SQL ON DELETE CASCADE, but you have to be careful to evict all Child entities belonging to the Parent you are about to delete.

If you already loaded a Parent's Child, when you delete the Parent, the Child will be deleted from the database without Hibernate knowing about the entity state change.

To address this situation, it's better to evict all associated Child entities, to make sure you don't accidentally re-persist them through some other associations transitive persistence.



Related Topics



Leave a reply



Submit