Say I have a unidirectional @ManyToOne
relationship like the following:
@Entity public class Parent implements Serializable { @Id @GeneratedValue private long id; } @Entity public class Child implements Serializable { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn private Parent parent; }
If I have a parent P and children C1…Cn referencing back to P, is there a clean and pretty way in JPA to automatically remove the children C1…Cn when P is removed (i.e. entityManager.remove(P)
)?
What I’m looking for is a functionality similar to ON DELETE CASCADE
in SQL.
Advertisement
Answer
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 thatEntityManager.remove
will remove the parent and the children. You can also specifyorphanRemoval
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 invokeEntityManager.clear()
after callingEntityManager.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.