假设我们有3个Entities对象类:
class Parent { String name; List<Child> children; } class Child { String name; Parent parent; } class Toy { String name; Child child; }
如何使用JPA2.x(或hibernate)批注来:
我正在使用Hibernate 4.3.5和mysql 5.1.30。
谢谢
如本文所述,remove 实体状态转换应从父级到子级联,而不是相反。
remove
您需要这样的东西:
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; }