Annotation Interface OnDelete
on delete action for a foreign key constraint.
The most common usage is @OnDelete(action = CASCADE).
@ManyToOne @OnDelete(action = CASCADE) Parent parent;This code results in an
on delete cascade clause in the DDL
definition of the foreign key.
The @OnDelete annotation may be applied to any field or
property representing an association or collection, or to a subclass
in a joined
inheritance hierarchy.
@Entity
@Inheritance(strategy = JOINED)
class Publication {
@Id
long id;
...
@ElementCollection
@OnDelete(action = CASCADE)
String<String> keywords;
}
@Entity
@OnDelete(action = CASCADE)
class Book extends Publication {
@Column(unique = true);
String isbn;
...
@ManyToMany
@OnDelete(action = CASCADE)
Set<Author> authors;
}
The affect of @OnDelete(action = CASCADE) is quite different
to CascadeType.REMOVE. It's more efficient
to delete a row via on delete cascade, but there's a catch.
Like database triggers, on delete actions can cause state held
in memory to lose synchronization with the database. In particular,
when an entity instance is deleted via on delete cascade, the
instance might not be removed from the second-level cache.
To alleviate this problem, @OnDelete may be used together with
cascade=REMOVE.
@OneToMany(mappedBy = Child_.parent, cascade = {PERSIST, REMOVE})
@OnDelete(action = CASCADE)
Set<Child> children = new HashSetinvalid input: '<'>();
This mapping looks redundant, but it's not.
- If
@OnDelete(action = CASCADE)is used in conjunction withcascade=REMOVE, then associated entities are fetched from the database, marked deleted in the persistence context, and evicted from the second-level cache. - If
@OnDelete(action = CASCADE)is used on its own, withoutcascade=REMOVE, then associated entities are not fetched from the database, are not marked deleted in the persistence context, and are not automatically evicted from the second-level cache.
Other options such as OnDeleteAction.SET_NULL and
OnDeleteAction.SET_DEFAULT are much less commonly used.
Note that @OnDelete(SET_DEFAULT) should be used together
with @ColumnDefault.
@ManyToOne
@OnDelete(action = OnDeleteAction.SET_DEFAULT)
@ColumnDefault("-1")
Parent parent;
-
Required Element Summary
Required ElementsModifier and TypeRequired ElementDescriptionThe action to taken by the database when deletion of a row would cause the constraint to be violated.
-
Element Details
-
action
OnDeleteAction actionThe action to taken by the database when deletion of a row would cause the constraint to be violated.
-