- v1 master doc: compassMap_v1.md
JPArelationships guide: JPA_Relationships_Guide.mdJPAannotations (xmlhistory): JPA Before Annotations one-to-many xmlJPAconceptsalbertprofewiki: DI / Relationships- Reference project: ApartmentPredictor github / Library3
Spring Boot Goal #2
Evolve the v1 pure-backend foundation (flat entities + H2) into a relational data model using JPA relationship annotations (@OneToMany, @ManyToOne, @OneToOne, @ManyToMany).
Three JPA tasks:
- Task 1 —
QuestionAndAnswer: turn the plain class into an@Entitylinked toQuestionandAnswervia@ManyToOne - Task 2 —
CustomerProfile: link the profiles toCustomer(@ManyToOne, a customer has many profiles) and to the recommendedRoadMaps (@ManyToMany) - Task 3 —
AssessmentView: turn the plain class into an@EntityaggregatingCustomer,List<QuestionAndAnswer>(@OneToMany) andCustomerProfile
Scope: entities, repositories, services and REST controllers only. No
Thymeleaf/views, no frontend in this version.
| Entity | Role | Relationships (v2) |
|---|---|---|
Customer |
person taking the assessment | 1..n AssessmentView, 1..n CustomerProfile |
Question |
question catalogue (per Dimension) |
1..n QuestionAndAnswer |
Answer |
a boolean answer value | 1..n QuestionAndAnswer |
QuestionAndAnswer |
question + answer + scoreContribution |
n..1 Question, n..1 Answer, n..1 AssessmentView |
CustomerProfile |
resulting profile (CodeProfile) + answers map |
n..1 Customer, n..n RoadMap (recommended, owning side) |
RoadMap |
learning path (stepsItemsSummary) |
n..n CustomerProfile (inverse) |
AssessmentView |
one assessment run: customer, timestamp, Q&A list, resulting profile | n..1 Customer, 1..n QuestionAndAnswer, n..1 CustomerProfile |
classDiagram
Customer "1" --> "*" AssessmentView
AssessmentView "1" --> "*" QuestionAndAnswer
QuestionAndAnswer "*" --> "1" Question
QuestionAndAnswer "*" --> "1" Answer
AssessmentView "*" --> "1" CustomerProfile
Customer "1" --> "*" CustomerProfile
CustomerProfile "*" <--> "*" RoadMap : recommendedRoadmaps
In
v1, every entity lived in its own table with no foreign keys:CustomerProfilestored answers as an@ElementCollectionmap andQuestionAndAnswer/AssessmentViewwere not even entities. Inv2we map the real-world relationships — one assessment contains many question/answer pairs, each pair points to one question and one answer, and each assessment produces one customer profile — into the database and Java code.
- One Customer takes an assessment
- One AssessmentView records the run: timestamp, number of questions, the
List<QuestionAndAnswer>and the resultingCustomerProfile - Many QuestionAndAnswer rows per assessment; each one references one Question and one Answer
- Many CustomerProfiles per customer (e.g. one per assessment run, the profile can evolve over time), each recommending many RoadMaps; the same RoadMap can be recommended to many CustomerProfiles
@ManyToOne+@JoinColumn(name = "..._id")goes on the owning side — the table that stores the FK column@OneToMany(mappedBy = "...", cascade = CascadeType.ALL, fetch = FetchType.LAZY)goes on the inverse side —mappedBynames the field on the owning side that controls the relationshipcascade = CascadeType.ALL: saving/deleting the parent propagates to childrenfetch = FetchType.LAZY: collections load on demand (avoids pulling whole object graphs)@OneToOne: FK on the owning side; usemappedByon the inverse side@ManyToMany+@JoinTable: no FK column in either entity table — JPA creates a join table with two FKs;@JoinTablegoes on the owning side,mappedByon the inverse side
From plain class to the join entity between Question and Answer:
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class QuestionAndAnswer {
@Id
private String id;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@ManyToOne
@JoinColumn(name = "answer_id")
private Answer answer;
@ManyToOne
@JoinColumn(name = "assessment_view_id")
private AssessmentView assessmentView;
private Double scoreContribution;
}What this means:
@Entity/@Id: the class becomes a persistent table (question_and_answer)@ManyToOneonquestion: many Q&A rows can reference the sameQuestion(the catalogue is reused across assessments)@JoinColumn(name = "question_id"): FK column inquestion_and_answer@ManyToOneonassessmentView: owning side of theAssessmentView ↔ QuestionAndAnswerrelationship (see Task 3)
Database structure created:
question_and_answer |
|
|---|---|
id |
PK |
question_id |
FK → question.id |
answer_id |
FK → answer.id |
assessment_view_id |
FK → assessment_view.id |
score_contribution |
double |
Answeralso needs@Entity+@Id(currently commented out) to be a valid@ManyToOnetarget.
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CustomerProfile {
@Id
private String id;
@Enumerated(EnumType.STRING)
private CodeProfile codeProfile;
private String name;
private String description;
private String goal;
// answers of the customer per dimension — kept from v1
@ElementCollection
private Map<Dimension, Boolean> profileAnswers;
// a customer can have many profiles (owning side)
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
// recommended roadmaps (owning side)
@ManyToMany(cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
@JoinTable(name = "customer_profile_roadmap",
joinColumns = @JoinColumn(name = "customer_profile_id"),
inverseJoinColumns = @JoinColumn(name = "roadmap_id"))
private List<RoadMap> recommendedRoadmaps;
}// RoadMap.java (inverse side)
@ManyToMany(fetch = FetchType.EAGER,
mappedBy = "recommendedRoadmaps")
@JsonIgnore
@EqualsAndHashCode.Exclude
private List<CustomerProfile> profiles;What this means:
@ManyToOneoncustomer: one customer can have many profiles (one per assessment, profile evolves over time); each profile belongs to one customer;customer_idFK lives incustomer_profile(not unique, unlike@OneToOne)@ManyToManyonrecommendedRoadmaps: one profile recommends many roadmaps, and one roadmap (shared template) is recommended to many profiles@JoinTable(name = "customer_profile_roadmap"):CustomerProfileis the owning side — it controls the join table;joinColumnsis the FK to this entity,inverseJoinColumnsthe FK to the other onemappedBy = "recommendedRoadmaps"onRoadMap.profiles: inverse side — read-only navigation, no extra table; adding a profile toroadMap.getProfiles()alone is not persisted@JsonIgnore: breaks the infiniteprofile → roadmaps → profiles → ...JSON loop@EqualsAndHashCode.Exclude: breaks the Lombok@DatahashCode()/equals()recursion between both sides@ElementCollectionprofileAnswers: stays as the per-dimension answers table (customer_profile_profile_answers) — basic-type map, not an entity relationship
Database structure created:
customer_profile |
|
|---|---|
id |
PK |
customer_id |
FK → customer.id |
customer_profile_roadmap (join table) |
|
|---|---|
customer_profile_id |
FK → customer_profile.id |
roadmap_id |
FK → road_map.id |
v2evolution: the first draft used@ManyToOne+roadmap_idFK incustomer_profile(one roadmap per profile). Moving to@ManyToManylets each profile recommend several roadmaps (e.g.P01→RM01..RM05, see roadmaps.json and profiles.json). Withddl-auto=updatethe oldroadmap_idcolumn stays incustomer_profileunused.
Check it in h2-console:
SELECT * FROM CUSTOMER_PROFILE;
SELECT * FROM ROAD_MAP;
SELECT * FROM CUSTOMER_PROFILE_ROADMAP;Inverse side (optional, add if navigation is needed):
// Customer.java
@OneToMany(mappedBy = "customer", fetch = FetchType.LAZY)
@JsonIgnore
@EqualsAndHashCode.Exclude
private List<CustomerProfile> profiles;
v2evolution: the first draft used@OneToOne(one profile per customer,customer_idwith a unique constraint). Withddl-auto=updatethat unique constraint is not dropped — recreate the DB (orddl-auto=createonce) after switching to@ManyToOne.
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AssessmentView {
@Id
private String id;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
private Instant timestamp;
private int qtyQuestions;
@OneToMany(mappedBy = "assessmentView", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<QuestionAndAnswer> questionsAndAnswers;
@ManyToOne
@JoinColumn(name = "customer_profile_id")
private CustomerProfile profile;
}What this means:
@ManyToOneoncustomer: one customer can run many assessments;customer_idFK inassessment_view@OneToMany(mappedBy = "assessmentView", cascade = ALL): the assessment owns its Q&A rows — saving anAssessmentViewcascades to allQuestionAndAnswerchildren;mappedBydelegates the FK toquestion_and_answer.assessment_view_id(no join table)@ManyToOneonprofile: the resulting profile is looked up, not owned — assessments reference sharedCustomerProfiletemplates
Database structure created:
assessment_view |
|
|---|---|
id |
PK |
customer_id |
FK → customer.id |
timestamp |
instant |
qty_questions |
int |
customer_profile_id |
FK → customer_profile.id |
- Don't forget bidirectional consistency — when adding/removing
QuestionAndAnsweruse a helper (addQuestionAndAnswer) that sets both sides - Don't use
EAGERon large collections — keepLAZYon@OneToMany @Data+ relationships: LomboktoString()/equals()traverse both sides and can loop or trigger lazy loads — exclude relationship fields if needed (@ToString.Exclude)orderis reserved in H2 —Question.orderalready maps toquestion_order- N+1 risk on
AssessmentView.questionsAndAnswers— plan aJOIN FETCHquery or@EntityGraphin the repository @ManyToMany+CascadeType.ALL/REMOVE— deleting a profile also deletes roadmaps shared with other profiles; prefer{PERSIST, MERGE}in productionEAGERon both sides of a@ManyToMany— loads the whole graph (profile → roadmaps → profiles ...); keep the inverse sideLAZYwhen data grows
AssessmentViewRestController exposes one assessment run at /api/v1/assessments:
POST /createcreates the whole aggregate in one call: theAssessmentView, itsQuestionAndAnswerrows and theirAnswers (composition, saved byCascadeType.ALL)Customer,CustomerProfileandQuestionare associations: they must already exist and are sent by id only ({"id": "..."}); the service loads the real entities and fails if an id is unknownAssessmentViewService.createAssessmentView(...)generates the ids, setstimestamp, links each Q&A to the assessment withaddQuestionAndAnswer(...)(owning side →assessment_view_id), computesqtyQuestionsand saves oncequestionsAndAnswersisWRITE_ONLY: accepted in the request, not returned; read it withGET /questionsAndAnswers?id=..., and the score withGET /score?id=...DELETE /byIdremoves the assessment and, by cascade, its Q&A rows and answers- Jackson 3 (Spring Boot 4):
spring.jackson.deserialization.fail-on-null-for-primitives=falseis needed because the request omits primitive fields (qtyQuestions,Question.order/weight)
Tasks to do:
-
QuestionAndAnswerRepository— exists; addfindByAssessmentViewId(...) -
AnswerRepository— new, onceAnsweris an entity -
AssessmentViewRepository— new -
AssessmentViewRestController—GET /assessments,POST /assessments(submit questionnaire, compute profile) -
PopulatorDB— seed questions, answers, roadmaps, profiles, one sample assessment
Same as v1: Java 21, Spring Boot, Spring Data JPA, H2, Lombok, IntelliJ IDEA.
