Here is my data model (simplified),
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;
}
}
I want to delete a full group from my addressbook, and all the people belonging to this group. So I do something like:
adressBook.getPeople().removeAll(peopleBelongingToGroupA);
adressBook.getGroups().remove(groupA);
But when my transaction is committed, Hibernate does first:
delete from groups where groupName='groupA';
Instead of deleting the people first. That causes my FOREIGN_KEY constraint between people and group to be violated.
Is there a way to tell hibernate to delete the people first, then the groups? Is there a flaw in my model?
Have you tried putting setting the cascade on each @ManyToOne. You’ve only specified, in many ways, cascade deletion on the AddressBook. This property is for each association I believe.
The EJB3.0 specification is well worth having to hand when writing these beans. See http://jcp.org/en/jsr/detail?id=220
Update:
Reading your datamodel again, there may be a missing annotation on people here that would explain the behaviour. Do you have cascade set on the link with people->group? This would explain why the first statement would first start by trying to delete the group. Presumably you would want an annotation for groups on people that does not cascade?