Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

EclipseLink/Examples/JPA/DeleteCascade


EclipseLink (as of 2.2) supports delete cascade constraints in the database. Most databases support a ON DELETE CASCADE option when defining foreign key constraints. This will cause the rows in the source table of this constraint to be automatically deleted when the parent row in the target table of the constraint is deleted.

EclipseLink supports delete cascading constraints using its @CascadeOnDelete annotation or <cascade-on-delete> xml element. The @CascadeOnDelete annotation can be used on any relationship where the target defines as foreign key to the source Entity. The annotation is placed on the source relationship. These include @OneToOne, @OneToMany, @ManyToMany and @ElementCollection It can also be used on a class with a @SecondaryTable or JOINED inheritance.

EclipseLink will both generate the DDL for the delete cascade on the foreign key constraint, and omit the delete SQL for the relationship. For a @OneToOne or @OneToMany, the @CascadeOnDelete should only be used if the relationship is a dependent relationship and has remove cascading or orphan removal. The @OneToOne must be using a mappedBy, as the constraint can only be delete cascaded in the inverse direction of the constraint. For a @ManyToMany or @ElementCollection only the join table (or collection table) will be deleted, the target Entity of a @ManyToMany can not be deleted by a delete cascade constraint.

Previous to 2.2 a delete cascade could still be defined on a constraint through a user defined DDL script. If set to cascade the relationship EclipseLink would still issue a delete SQL for the relationship, which would still work, just require an extra SQL. If not set to cascade the relationship EclipseLink would do nothing, but would not be aware that the object had been removed.

Example CascadeOnDelete

@Entity
@SecondaryTable(name="EMP_SALARY")
@CascadeOnDelete
public class Employee{
    @Id
    private long id;
    private String firstName;
    private String lastName;
    @Column(table="EMP_SALARY")
    private String salary;
    @OneToOne(mappedBy="owner", orphanRemoval=true, cascade={CascadeType.ALL})
    @CascadeOnDelete
    private Address address;
    @OneToMany(mappedBy="owner", orphanRemoval=true, cascade={CascadeType.ALL})
    @CascadeOnDelete
    private List<Phone> phones;
    @ManyToMany
    @JoinTable(name="EMP_PROJ")
    @CascadeOnDelete
    private List<Project> projects;
    ...
}

Back to the top