Delete child from parent and parent from child automatically with JPA annotations
The remove
entity state transition should cascade from parent to children, not the other way around.
You need something like this:
class Parent {
String name;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
List<Child> children = new ArrayList<>();
public void addChild(Child child) {
child.setParent(this);
children.add(child);
}
public void removeChild(Child child) {
children.remove(child);
child.setParent(null);
}
}
class Child {
String name;
@ManyToOne
Parent parent;
@OneToOne(mappedBy = "child", cascade = CascadeType.ALL, orphanRemoval = true)
Toy toy;
}
class Toy {
String name;
@OneToOne
Child child;
}
You should use CascadeType.REMOVE
. This is common annotation for both Hibernate and JPA. Hibernate has another similar type CacadeType
like CascadeType.DELETE
.
Delete all children automatically when parent delete (one to many)
class Parent { String name; @OneToMany(cascade = CascadeType.REMOVE) List<Child> children; }
Delete child automatically from children list when it is deleted (many to one)
class Child { String name; @ManyToOne(cascade = CascadeType.REMOVE) Parent parent; }
Delete toy automatically when child remove (one to one)
class Toy { String name; @OneToOne(cascade = CascadeType.REMOVE) Child child; }