英文:
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 = "paper_mcq",
joinColumns = {@JoinColumn(name = "paper_id")},
inverseJoinColumns = {@JoinColumn(name = "mcq_id")})
@JsonIgnore
private Set<Mcq> mcqs = new HashSet<>();
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论