在Hibernate中级联删除

在Hibernate中级联删除

本文介绍了“删除哪里”在Hibernate中级联删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过其中一个外键级联删除连接表中的行,并且还有另一个与之相关的表,我想删除与此ID关联的所有行。所以它看起来像下图。当我用休眠Session.delete(reqCandObject)时,它工作正常,级联通过从candidate_jobReq表中删除一个条目以及相关的注释。不过,我想删除的有某候选人ID(也删除评论)我试过以下,但不同的是漂亮的hibernate.delete(对象)函数的函数,这一个candidate_jobReq项的所有的运行到外键约束错误。如何删除这些行,而让hibernate级联删除我?



 公共无效deleteWhere(字符串selectionCase){
会话hibernateSession =此.getSession();
尝试{
hibernateSession.beginTransaction();
Query q = hibernateSession.createQuery(delete+ type.getSimpleName()+where+ selectionCase);
q.executeUpdate();
hibernateSession.getTransaction()。commit();
} finally {
hibernateSession.close();



$ div class =h2_lin>解决方案

Hibernate在内部处理级联。执行 delete 查询不会触发内部级联,这将导致不一致/孤儿。你可能已经尝试过并且遇到外键约束错误。

有两种方法可以删除实体列表以及它们的子实体:


  1. 使用 selectionCase 选择实体列表。迭代整个列表并使用 session.delete 单独删除每个列表。

  2. 手动删除记录。分开写删除语句。为避免违反外键约束,您需要在删除父母之前删除子记录。这将比第一个选项更好。


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.

这篇关于“删除哪里”在Hibernate中级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:25