简体   繁体   English

Hibernate多对多自引用,如何删除没有级联?

[英]Hibernate many-to-many self-reference, how to delete without cascade?

I have a many-to-many relation on a single object with itself: 我对一个单独的对象有多对多的关系:

    <set name="relatedPersons" lazy="false"  table="PersonRelatedPerson" 
           cascade="none" >
    <key column="personId" foreign-key="fk_related_person" not-
        null="false"/>
       <many-to-many column="relatedPersonId" class="Person" not-found="ignore"/>
    </set>

as you can see I have set cascade to "none" because, when i delete one person, ofcourse i just would like to delete the relations from the table PersonRelatedPerson, and not the related Persons them selves. 正如你所看到的,我已经将级联设置为“无”,因为当我删除一个人时,当然我只想删除表PersonRelatedPerson中的关系,而不是相关人员他们自己。 When i try to do delete with this mapping, i get the ConstraintViolationException: Could not execute JDBC batch update.... 当我尝试使用此映射进行删除时,我得到ConstraintViolationException:无法执行JDBC批量更新....

I am guessing that it is somehow possible to delete this by hibernate by properly setting some mapping flags (or do i have to do some weird workarounds eg. first delete second person from set of first person, delete first person from set of second, and then delete first.... i really dont wanna do this :D) 我猜测通过正确设置一些映射标志(或者我必须做一些奇怪的解决方法,例如。首先从第一人的集合中删除第二人,从第二人集中删除第一人),以某种方式可以通过休眠删除它。然后先删除....我真的不想这样做:D)

Appreciate all the help!!! 感谢所有的帮助!

You'll just have to remove the relationships yourself. 你只需要自己删除这些关系。 To do this, before removing the person A, you'll have to find all the persons who have A in their set of related persons, and remove A from these sets. 要做到这一点,在移除A人之前,您必须找到所有在相关人员组中拥有A的人,并从这些集中删除A. If you don't, then of course you can't delete A because other persons still reference A. 如果你不这样做,那么你当然不能删除A,因为其他人仍然参考A.

Either do this with a HQL query and remove A from the sets of the found persons in Java, or use a dedicated SQL delete query to remove all the rows from the join table. 使用HQL查询执行此操作并从Java中找到的人员集中删除A,或使用专用SQL删除查询从联接表中删除所有行。 But be aware that this SQL query will bypass the caches (first-level and second-level, if any), and your session might thus hold an incorrect view of the database. 但请注意,此SQL查询将绕过缓存(第一级和第二级,如果有),因此您的会话可能会保留错误的数据库视图。

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

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