javajpajpa-2.0many-to-one

JPA: unidirectional many-to-one and cascading delete


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.


Solution

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