AssessmentView – Rebuild Q&A List

Visual walkthrough of the service method that rebuilds the bidirectional association
so both sides point to each other (owning side + inverse side).

1. Class Diagram – Cardinality, Owner & JPA

Owning side (holds the FK) Inverse side (mappedBy) Cascade / Composition Association (must already exist)
AssessmentView INVERSE
- id : String
- customer : Customer
- profile : CustomerProfile
- timestamp : Instant
- qtyQuestions : int
@OneToMany(mappedBy="assessmentView",
  cascade=ALL, fetch=LAZY)
@JsonProperty(WRITE_ONLY)
questionsAndAnswers : List<QuestionAndAnswer>
QuestionAndAnswer OWNING
- id : String
- scoreContribution : Double
@ManyToOne
@JoinColumn(name="question_id")
question : Question (assoc)
@OneToOne(cascade=ALL, orphanRemoval)
@JoinColumn(name="answer_id")
answer : Answer (comp)
@ManyToOne
@JoinColumn(name="assessment_view_id")
@JsonIgnore
assessmentView : AssessmentView
Question ASSOC
- id : String
- text, dimension, order, weight …
Answer COMPOSITION
- id : String
- value : Boolean
Cardinality
AssessmentView 1 ──── * QuestionAndAnswer  (composition, cascade ALL)
QuestionAndAnswer * ──── 1 Question  (association – load by id)
QuestionAndAnswer 1 ──── 0‥1 Answer  (composition, cascade ALL + orphanRemoval)

Why the rebuild is mandatory
Because 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.

2. The List – Three States

Visual representation of the List<QuestionAndAnswer> as it is processed.

INCOMING Client JSON → stubs only
[0]
Q&A id
null
Question
stub { id only }
Answer
value = true / false
[1]
Q&A id
null
Question
stub { id only }
Answer
value = true / false
[2]
Q&A id
null
Question
stub { id only }
Answer
value = true / false
↓ defensive copy + clear the collection
CLEARED assessmentView.setQuestionsAndAnswers(new ArrayList<>())
Empty list — no elements yet.
Ready to be rebuilt with fully managed entities.
↓ for each item → generate ids, load Question, call helper
REBUILT Both sides of the association are now set
[0]
Q&A id
UUID generated
Question
loaded from DB
Answer + back-ref
id set · → assessmentView
[1]
Q&A id
UUID generated
Question
loaded from DB
Answer + back-ref
id set · → assessmentView
[2]
Q&A id
UUID generated
Question
loaded from DB
Answer + back-ref
id set · → assessmentView

3. Code – Block by Block

Defensive copy of the incoming list

List<QuestionAndAnswer> incoming = assessmentView.getQuestionsAndAnswers() == null
        ? new ArrayList<>()
        : new ArrayList<>(assessmentView.getQuestionsAndAnswers());
Why? We need a stable snapshot of whatever the client sent. If the list is null we start with an empty one (safe for the for-loop). A new ArrayList avoids ConcurrentModification problems when we later clear the original collection.

Clear the collection on the aggregate root

assessmentView.setQuestionsAndAnswers(new ArrayList<>());
Why? We are about to rebuild the list from scratch with properly managed entities. Starting from an empty collection guarantees that only the elements we explicitly add (via the helper) will be present.

Loop – generate a new primary key for each Q&A

for (QuestionAndAnswer questionAndAnswer : incoming) {
    questionAndAnswer.setId(UUID.randomUUID().toString());
Why? Every QuestionAndAnswer is a brand-new entity created by this request. The client never supplies its id (same pattern as AssessmentView itself).

Validate that a Question id was provided

    if (questionAndAnswer.getQuestion() == null
            || questionAndAnswer.getQuestion().getId() == null) {
        throw new IllegalArgumentException(
            "QuestionAndAnswer requires an existing question id");
    }
Why? Question is an association, not a composition. The client must reference an already-persisted Question by id. Missing id → hard fail with a clear message.

Replace the stub Question with the real managed entity

    String questionId = questionAndAnswer.getQuestion().getId();
    questionAndAnswer.setQuestion(
        questionRepository.findById(questionId)
            .orElseThrow(() -> new IllegalArgumentException(
                "Question not found: " + questionId)));
Why? The JSON only contains {"id": "..."}. Hibernate needs a managed entity reference; otherwise it would try to insert a new (incomplete) Question. Unknown id → exception.

Ensure the Answer (composition) has an id

    if (questionAndAnswer.getAnswer() != null
            && questionAndAnswer.getAnswer().getId() == null) {
        questionAndAnswer.getAnswer().setId(UUID.randomUUID().toString());
    }
Why? Answer is owned by the Q&A (cascade ALL + orphanRemoval). It is created together with the Q&A, so we generate its primary key if the client omitted it.

Add via the helper – the critical bidirectional link

    assessmentView.addQuestionAndAnswer(questionAndAnswer);
}
Why this is the key line?
addQuestionAndAnswer does two things:
  1. Adds the Q&A to the collection (inverse side).
  2. Sets questionAndAnswer.setAssessmentView(this) (owning side).
Without step 2 the foreign-key column assessment_view_id would be saved as NULL.

4. The FK problem & how the helper solves it

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.

BEFORE helper Only the inverse collection is populated
AssessmentView (1)
questionsAndAnswers = [ qa0, qa1, qa2 ]
inverse side · mappedBy · ignored by Hibernate for FK
1 ─── *
QuestionAndAnswer (*)
assessmentView = null
owning side · holds the FK column
Result if we saved now
INSERT INTO question_and_answer (..., assessment_view_id) VALUES (..., NULL)
The many-side rows would be orphaned — no link back to the AssessmentView.
↓ assessmentView.addQuestionAndAnswer(qa)
AFTER helper Both sides are set — FK is ready
AssessmentView (1)
questionsAndAnswers = [ qa0, qa1, qa2 ]
inverse side · collection updated
1 ⟷ *
QuestionAndAnswer (*)
assessmentView = this
owning side · FK field now points to parent
What the helper does
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