“Delete Where” cascade delete in Hibernate?

…衆ロ難τιáo~ 提交于 2019-12-23 12:09:00

问题


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:

  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.


来源:https://stackoverflow.com/questions/19185791/delete-where-cascade-delete-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!