在@ManyToMany关系中更新后不想要的删除的问题。

huangapple go评论85阅读模式
英文:

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 = &quot;student_project&quot;,
            joinColumns = @JoinColumn(name = &quot;student_id&quot;),
            inverseJoinColumns = @JoinColumn(name = &quot;project_id&quot;))
    private Set&lt;Project&gt; projects;

Slave:

    @ManyToMany(mappedBy = &quot;projects&quot;, fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
    private Set&lt;Student&gt; 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集合与数据库同步。这与级联无关。这只是关系的所有权导致了这种情况。如果您合并的Studentprojection为空,那么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.

huangapple
  • 本文由 发表于 2023年2月26日 22:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定