Hibernate @OneToMany 在更新父对象时不会从列表中移除子对象。

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

Hibernate @OneToMany don't remove child from list when updating parent

问题

I have created a mapping between the Paper and Mcq question as follows.

public class Paper {
    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "paper_mcq",
        joinColumns = {@JoinColumn(name = "paper_id")},
        inverseJoinColumns = {@JoinColumn(name = "mcq_id")})
    @JsonIgnore
    private Set<Mcq> mcqs = new HashSet<>();
}

When I update the Paper entity, it deletes all MCQs.

SQL Output:

Hibernate: delete from paper_mcq where paper_id=?
英文:

I have create mapping between Paper and Mcq question as below.

    public class Paper {
 @OneToMany(fetch = FetchType.EAGER, cascade = 		{CascadeType.PERSIST, CascadeType.MERGE})
	 @JoinTable(name = &quot;paper_mcq&quot;,
        joinColumns = {@JoinColumn(name = &quot;paper_id&quot;)},
        inverseJoinColumns = {@JoinColumn(name = &quot;mcq_id&quot;)})
@JsonIgnore
private Set&lt;Mcq&gt; mcqs = new HashSet&lt;&gt;();

}

When I'm updating Paper entity it's deletes all MCQ.

SQL Output:

Hibernate: delete from paper_mcq where paper_id=?

答案1

得分: 1

我相信你在paperRepo.save(paper)中的paper对象此时没有mcqs,而级联操作将其视为删除。我只是假设你是从JSON中接收对象,@JsonIgnore只是忽略了反序列化。

所以有多种解决方法:

  • 查询mcqs并在更新之前设置它们
  • 删除@JsonIgnore并在JSON中添加它们
  • 删除级联操作并手动设置它
英文:

I believe your paper object in paperRepo.save(paper) don't have mcqs at this time, and the cascading sees that as a deletion. I'm just assuming that you're receiving your object from json and the @JsonIgnore simply ignores the deserialization.

So there are multiple options to solve that:

  • Query the mcqs and set them before updating
  • remove @JsonIgnore and add those in your json
  • remove the cascading and set it manually

huangapple
  • 本文由 发表于 2020年1月3日 23:47:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581447.html
匿名

发表评论

匿名网友

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

确定