简体   繁体   中英

“Delete Where” cascade delete in Hibernate?

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();
    }
}

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:

  1. Select the list of entities using selectionCase . Iterate through the list and delete each one individually using session.delete .
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM