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

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

我有一个关于多对五关系的严重问题。我只把组边的关系映射如下

<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>

通过删除尝试,我遇到了以下情况:

  1. 通过删除一个组,该组和关联的所有学生 已删除。

  2. 通过尝试删除学生,我收到异常:

    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`))
    

我希望我的程序只删除我传递给它的实体和绑定到它的连接记录。

如果你能提供任何帮助,我将不胜感激。

如果你想删除一个 Student 你必须这样做:

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