Gautam Singh
Gautam Singh

Reputation: 37

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

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=?

Upvotes: 0

Views: 276

Answers (1)

Marc N&#252;tzel
Marc N&#252;tzel

Reputation: 56

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

Upvotes: 1

Related Questions