Jump to: navigation, search

EclipseLink/Examples/JPA/DeleteCascade

< EclipseLink‎ | Examples‎ | JPA
Revision as of 12:22, 25 January 2011 by James.sutherland.oracle.com (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


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 constraint 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.

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;
    ...
}