英文:
Hibernate unwanted delete after update in @ManyToMany relationship
问题
以下是要翻译的代码部分:
主实体:
@ManyToMany
@JoinTable(
name = "student_project",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "project_id"))
private Set<Project> projects;
从属实体:
@ManyToMany(mappedBy = "projects", fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private Set<Student> students;
当我更新项目时,一切似乎正常。但是当我更新学生时,与学生ID相关的学生项目表中的所有关系都消失了。我认为这与主表中的级联字段有关,但我不确定。应该是什么样子?或者可能是其他原因?
顺便说一句,我使用em.merge(student) / em.merge(project)合并两个实体。
英文:
Here are my entities <br>
Master:
@ManyToMany
@JoinTable(
name = "student_project",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "project_id"))
private Set<Project> projects;
Slave:
@ManyToMany(mappedBy = "projects", fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private Set<Student> students;
When I update project, everything seems fine. But when I update student, all relations in the student_project table with the students id are gone.
I think it has something to do with the cascade field in the master table, but I am not sure. How should it look like? Or maybe it is something else?
Btw I merge both entities using em.merge(student) / em.merge(project)
答案1
得分: 0
关系的拥有方是Student
。因此,当您合并一个脱离状态的Student
对象时,Hibernate会将projects
集合与数据库同步。这与级联无关。这只是关系的所有权导致了这种情况。如果您合并的Student
的projection
为空,那么student_project
中的所有现有项目将被删除,以适应该学生。
英文:
The owning side of the relationship is Student
. So when you merge a detached Student
object, Hibernate will synchronize the projects
collection with the database. This has nothing to do with cascading. That's just simply the relationship ownership that causes this. If the projection
of that Student
you merge are empty, all existing projects from student_project
will be deleted for that student.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论