2020-06-28

Hibernate JPA @OnDelete Example

@OnDelete

The @OnDelete annotation is used to specify the delete strategy employed by the currently annotated collection, array or joined subclasses. This annotation is used by the automated schema generation tool to generated the appropriate FOREIGN KEY DDL cascade directive.

The two possible strategies are defined by the OnDeleteAction enumeration:

CASCADE
Use the database FOREIGN KEY cascade capabilities.

NO_ACTION
Take no action.

OnDelete
Strategy to use on collections, arrays and on joined subclasses delete. OnDelete of secondary tables currently not supported.

@OnDelete cascade

While the previous cascade types propagate entity state transitions, the @OnDelete cascade is a DDL-level FK feature which allows you to remove a child record whenever the parent row is deleted.

So, when annotating the @ManyToOne association with @OnDelete( action = OnDeleteAction.CASCADE ), the automatic schema generator will apply the ON DELETE CASCADE SQL directive to the Foreign Key declaration, as illustrated by the following example.

Example : @OnDelete @ManyToOne mapping

@Entity(name = "Person")
public static class Person {

@Id
private Long id;

private String name;

//Getters and setters are omitted for brevity

}
@Entity(name = "Phone")
public static class Phone {

@Id
private Long id;

@Column(name = "`number`")
private String number;

@ManyToOne(fetch = FetchType.LAZY)
@OnDelete( action = OnDeleteAction.CASCADE )
private Person owner;

//Getters and setters are omitted for brevity

}

@OnDelete @OneToMany mapping

@Entity(name = "Person")
public static class Person {

@Id
private Long id;

private String name;

@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
private List<Phone> phones = new ArrayList<>();

//Getters and setters are omitted for brevity

}
@Entity(name = "Phone")
public static class Phone {

@Id
private Long id;

@Column(name = "`number`")
private String number;

@ManyToOne(fetch = FetchType.LAZY)
private Person owner;

//Getters and setters are omitted for brevity

}

No comments:

Post a Comment