Visual walkthrough of the service method that rebuilds the bidirectional association
so both sides point to each other (owning side + inverse side).
QuestionAndAnswer is the owning side,
Hibernate only looks at questionAndAnswer.assessmentView when writing the FK.
The collection on AssessmentView is ignored for persistence.
→ We must call addQuestionAndAnswer() so both sides are set.
Visual representation of the List<QuestionAndAnswer> as it is processed.
List<QuestionAndAnswer> incoming = assessmentView.getQuestionsAndAnswers() == null
? new ArrayList<>()
: new ArrayList<>(assessmentView.getQuestionsAndAnswers());
assessmentView.setQuestionsAndAnswers(new ArrayList<>());
for (QuestionAndAnswer questionAndAnswer : incoming) {
questionAndAnswer.setId(UUID.randomUUID().toString());
if (questionAndAnswer.getQuestion() == null
|| questionAndAnswer.getQuestion().getId() == null) {
throw new IllegalArgumentException(
"QuestionAndAnswer requires an existing question id");
}
String questionId = questionAndAnswer.getQuestion().getId();
questionAndAnswer.setQuestion(
questionRepository.findById(questionId)
.orElseThrow(() -> new IllegalArgumentException(
"Question not found: " + questionId)));
{"id": "..."}.
Hibernate needs a managed entity reference; otherwise it would try to insert a new (incomplete) Question.
Unknown id → exception.
if (questionAndAnswer.getAnswer() != null
&& questionAndAnswer.getAnswer().getId() == null) {
questionAndAnswer.getAnswer().setId(UUID.randomUUID().toString());
}
assessmentView.addQuestionAndAnswer(questionAndAnswer); }
addQuestionAndAnswer does two things:
questionAndAnswer.setAssessmentView(this) (owning side).assessment_view_id would be saved as NULL.
In a bidirectional association the many side owns the foreign key.
Hibernate only looks at the field annotated with @JoinColumn when writing the database row.
INSERT INTO question_and_answer (..., assessment_view_id) VALUES (..., NULL)public void addQuestionAndAnswer(QuestionAndAnswer qa) {
this.questionsAndAnswers.add(qa); // 1. inverse side
qa.setAssessmentView(this); // 2. owning side ← sets the FK
}
Now Hibernate will write the correct value into the assessment_view_id column.
After the loop, qtyQuestions is set to the size of the rebuilt list
and a single assessmentViewRepository.save(assessmentView) is called.
Because of CascadeType.ALL on both the OneToMany and the OneToOne,
every QuestionAndAnswer and every Answer is persisted in the same transaction.
The owning-side FK is correctly populated thanks to the helper method.
Diagram for the CompassMap AssessmentView service · based on assessmentview-rest-v2.md