我在从数据库中删除父实体时遇到问题。代码如下所示:
public class Parent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="parentId")
private Set<Child> children = new HashSet<Child>();
}
public class Child implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String name;
}
Query q = em.createQuery("delete from Parent");
q.executeUpdate();
但我收到“错误:表“parent”上的更新或删除违反了表“child”上的外键约束“fk2f04da924aeb47d8”。是不是不能级联删除所有的children?否则你应该如何清理表格?
最佳答案
批量删除操作不是级联的。来自 JPA 1.0 规范:
4.10 Bulk Update and Delete Operations
(...)
A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.
(...)
因此,如果您想使用批量删除,则必须“手动”处理关系(即先删除相关实体)。
另一种选择是在父实体上循环并调用 em.remove()
(级联会起作用)。
选择一个选项或另一个选项将取决于要删除的实体数量和预期性能。
关于java - 删除父项和所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3150651/