Hibernate bidirectional One-to-Many Cascade.All not working

Viewed 2649

I have the following two class Answer and SubAnswer:

@Entity
public class Answer {
    @OneToMany(mappedBy = "answer", orphanRemoval = true, cascade = {CascadeType.ALL})
    List<SubAnswer> subAnswers;
}
public class SubAnswer {
    @ManyToOne(optional = false)
    Answer answer;
}

and I save them like this

{
   Answer ans = new Answer();
   List<SubAnswer> subAnswerList = new ArrayList<SubAnswer>();
   ans.setSubAnswers(subAnswerList);
   ans.add(new SubAnswer());
   ans.add(new SubAnswer());
   entityManager.save(ans);
}

when I save an Answer, I think it should save the SubAnswers and it saves them but it does not set the SubAnswer.answer field and it remain null

1 Answers

I honestly couldn't say if this is good / bad practice but I've had a similar problem and fixed it by using the following:

@Entity
public class Answer {
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "answer_id")
    List<SubAnswer> subAnswers;
}

@Entity
public class SubAnswer {
    @ManyToOne
    @JoinColumn(name = "answer_id")
    Answer answer;
}

This gives you a 'answer_id' column in your SubAnswer table and allows you to perform your:

{
   Answer ans = new Answer();
   List<SubAnswer> subAnswerList = new ArrayList<SubAnswer>();
   ans.setSubAnswers(subAnswerList);
   ans.add(new SubAnswer());
   ans.add(new SubAnswer());
   entityManager.save(ans);
}

and still get the answer_id populated.

On a side note, I'm barely getting started with hibernate so if anyone has any opinions on whether this ok or a truly terrible solution I'd appreciate hearing about that!

Related