简体   繁体   English

在Hibernate中“删除Where”级联删除?

[英]“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. 我试图通过其中一个外键级联删除连接表中的行,并且它有另一个与之相关的表,我想删除与此ID关联的所有行。 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. 当我使用带有hibernate的Session.delete(reqCandObject)时,它可以正常工作,并通过删除candidate_jobReq表中的One条目以及相关的注释来实现级联。 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. 但是,我想删除所有具有特定候选ID的candidate_jobReq条目(并且还删除注释)我尝试了下面的函数,但不同于漂亮的hibernate.delete(对象)函数,这一个遇到外键约束错误。 How can I delete these rows while having hibernate cascade the delete for me? 如何在为hibernate级联删除时删除这些行?

在此输入图像描述

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. Hibernate在内部处理级联。 Executing a delete query won't trigger the internal cascades, which will result in inconsistencies / orphans. 执行delete查询不会触发内部级联,这将导致不一致/孤立。 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 . 使用selectionCase实体列表。 Iterate through the list and delete each one individually using session.delete . 遍历列表并使用session.delete单独删除每个列表。
  2. Delete the records manually. 手动删除记录。 Write separate delete statements. 编写单独的delete语句。 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. 这将比第一个选项表现更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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