使用 JPA 注释自动从父项中删除子项和从子项中自动删除父项 [英] Delete child from parent and parent from child automatically with JPA annotations
本文介绍了使用 JPA 注释自动从父项中删除子项和从子项中自动删除父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有 3 个实体对象类:
Suppose that we have 3 Entities object class:
class Parent {
String name;
List<Child> children;
}
class Child {
String name;
Parent parent;
}
class Toy {
String name;
Child child;
}
我如何使用 JPA2.x(或休眠)注释来:
How can I use JPA2.x (or hibernate) annotations to:
- 父删除时自动删除所有子项(一对多)
- 删除子项时自动从子项列表中删除子项(多对一)
- 当孩子移除时自动删除玩具(一对一)
我使用的是 Hibernate 4.3.5 和 mysql 5.1.30.
I'm using Hibernate 4.3.5 and mysql 5.1.30.
谢谢
推荐答案
remove
实体状态转换应该从父级到子级级联,而不是相反.
The remove
entity state transition should cascade from parent to children, not the other way around.
你需要这样的东西:
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;
}
这篇关于使用 JPA 注释自动从父项中删除子项和从子项中自动删除父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文