简体   繁体   中英

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.getGroups().remove(student);
entityManager.remove(student);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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