java – 使用JPA注释自动从子进程中删除子进程和子进程中的子进程
作者:互联网
假设我们有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.
谢谢
解决方法:
正如this article中所解释的,删除entity state transition应该从父级到子级级联,而不是相反.
你需要这样的东西:
class Parent {
String name;
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
List<Child> children;
public void addChild(Child child) {
child.setParent(this);
children.add(child);
}
public void removeChild(Child child) {
children.remove(child);
if (child != null) {
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;
}
标签:java,orm,jpa,hibernate,hibernate-mapping 来源: https://codeday.me/bug/20190930/1835177.html