简体   繁体   English

如何在多对多Hibernate关联中仅删除实体及其连接记录

[英]How to delete just the entity and its join record in a many-to-many Hibernate association

I have a serious issue with a many-to-may relationship. 我与多对多关系有一个严重的问题。 I only mapped the relationship on the side of the group as follows 我只将关系映射到组的一侧,如下所示

<class mutable="true" name="entities.Group" table="StudGroup">
 ...
 <set lazy="false" cascade="save-update" name="studentSet" table="stud_group_join">
<key column="groupId"/>
<many-to-many class="entities.Student" column="studId"/>
</set>
...
</class>

By deletion attempts I experience the following: 通过删除尝试,我会遇到以下问题:

  1. By deleting a group, the group and all the students associated with it are deleted. 通过删除组,该组和与之关联的所有学生都将被删除。

  2. By attempting to delete a student, I recieve an Exception: 通过尝试删除学生,我收到异常:

     com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`students`.`stud_group_join`, CONSTRAINT `FK30E5217826CEA4E5` FOREIGN KEY (`studId`) REFERENCES `student` (`id`)) 

I would like my program to only delete the entity I passed to and the join record, bound to it. 我希望程序只删除传递给它的实体和绑定到它的联接记录。

Any help of yours I will appreciate. 您的任何帮助,我将不胜感激。

If you want to delete a Student you'll have to do it like this: 如果要删除Student ,则必须这样做:

student.getGroups().remove(student);
entityManager.remove(student);

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

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