问题
I am trying to cascade delete rows in a join table via one of its foreign keys and it has another table related to it that I would like to remove all rows associated with this ID as well. So it looks like the diagram below. When I use Session.delete(reqCandObject) with hibernate it works fine and cascades through deleting the One entry from the candidate_jobReq table as well as the associated comments. However, I want to delete all of the candidate_jobReq entries that have a certain candidate ID (and also delete the comments) I tried the function below but unlike the nice hibernate.delete(object) function, this one runs into a foreign key constraint error. How can I delete these rows while having hibernate cascade the delete for me?
public void deleteWhere(String selectionCase){
Session hibernateSession = this.getSession();
try {
hibernateSession.beginTransaction();
Query q = hibernateSession.createQuery("delete "+ type.getSimpleName() +" where " + selectionCase);
q.executeUpdate();
hibernateSession.getTransaction().commit();
} finally {
hibernateSession.close();
}
}
回答1:
Hibernate handles cascades internally. Executing a delete
query won't trigger the internal cascades, which will result in inconsistencies / orphans. This you might have tried and faced foreign key constraint error.
There are two ways to delete a list of entities along with their child entities:
- Select the list of entities using
selectionCase
. Iterate through the list and delete each one individually usingsession.delete
. - Delete the records manually. Write separate
delete
statements. To avoid the violation of foreign key constraints, you need to delete child records before deleting the parents. This will perform better than the first option.
来源:https://stackoverflow.com/questions/19185791/delete-where-cascade-delete-in-hibernate