[英]On delete set null in hibernate in @OneToMany
我有一個部門實體,其關系如下:
許多部門可以在一個父部門中:
@ManyToOne @JoinColumn(name = "ik_parent_department_id") private Department parentDepartment;
一個上級部門可以有多個部門:
@OneToMany(mappedBy = "parentDepartment") private Set<Department> children = new HashSet<Department>(0);
我想實現下一個:當我刪除一個部門時,這個部門的所有孩子的ik_parent_department_id參數被設置為null 。 任何想法如何做到這一點?
您必須將孩子的ik_parent_department_id
顯式設置為 null。
Department parentDepartment = (Department) session.load(Department.class, id);
session.delete(parentDepartment);
for (Department child : parentDepartment.getChildren()){
child.setParentDepartment(null);
}
session.flush();
通過級聯,您只能設法刪除子Departments
。
使用 JPA,在父Entity
您可能有類似的東西
@OneToMany(mappedBy="parent", cascade={CascadeType.PERSIST})
Collection<Child> children;
並且為了避免在父Entity
執行父刪除時可能出現的重復“設置空代碼”和完整性違規異常
@PreRemove
private void preRemove() {
children.forEach( child -> child.setParent(null));
}
只需編碼:
for (Department child : parent.getChildren()) {
child.setParentDepartment(null);
}
session.delete(parent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.