这是我的数据模型(简化版),
public class AddressBook {
private List<Group> groups = new ArrayList<Group>();
private List<People> peoples = new ArrayList<People>();
@OneToMany(mappedBy = "addressbook", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<Group> getGroups() {
return groups;
}
@OneToMany(mappedBy = "addressbook", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<People> getPeoples() {
return peoples;
}
}
public class Group {
private AddressBook addressBook;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
public void setAddressBook(AddressBook addressBook) {
this.addressBook = addressBook;
}
}
public class People {
private AddressBook addressBook;
private Group group;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
public AddressBook getAddressBook() {
return addressBook;
}
public Group getGroup() {
return group;
}
}
我想从我的通讯录中删除一个完整的分组,以及属于该组的所有联系人。因此我会执行以下操作:
adressBook.getPeople().removeAll(peopleBelongingToGroupA);
adressBook.getGroups().remove(groupA);
但是当我的事务提交时,Hibernate 首先会执行以下操作:
delete from groups where groupName='groupA';
不要先删除人员。这会导致我的“people”和“group”之间的FOREIGN_KEY约束被违反。
有没有办法告诉Hibernate先删除人员,然后再删除组?我的模型有什么缺陷吗?