Bird
Raised Fist0
Spring Bootframework~10 mins

@OneToMany relationship in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - @OneToMany relationship
Define Parent Entity
Add @OneToMany on Collection
Define Child Entity
Add @ManyToOne on Child
Save Parent with Children
Spring Boot persists Parent and Children
Retrieve Parent loads Children
This flow shows how a parent entity holds a collection of child entities using @OneToMany, and how Spring Boot saves and loads them together.
Execution Sample
Spring Boot
import javax.persistence.*;
import java.util.List;

@Entity
class Parent {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
  private List<Child> children;

  // getters and setters
}

@Entity
class Child {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToOne
  @JoinColumn(name = "parent_id")
  private Parent parent;

  // getters and setters
}
Defines a Parent entity with a list of Child entities linked by @OneToMany and @ManyToOne annotations.
Execution Table
StepActionParent.childrenChild.parentDatabase Operation
1Create Parent object[]nullNo DB operation
2Create Child1 object[]nullNo DB operation
3Set Child1.parent = Parent[]ParentNo DB operation
4Add Child1 to Parent.children[Child1]ParentNo DB operation
5Save Parent[Child1]ParentInsert Parent, Insert Child1 with FK to Parent
6Retrieve Parent from DB[Child1]ParentSelect Parent, Select Children where FK matches
7Access Parent.children[Child1]ParentChildren loaded from DB
8Exit[Child1]ParentAll entities persisted and linked
💡 Execution stops after Parent and its Children are saved and retrieved with correct links.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5Final
Parent.childrennull[][Child1][Child1][Child1]
Child1.parentnullnullParentParentParent
Key Moments - 2 Insights
Why do we set Child.parent before adding Child to Parent.children?
Because the @ManyToOne side owns the relationship, setting Child.parent ensures the foreign key is correct in the database, as shown in execution_table step 3 and 4.
What happens if we save Parent without setting Child.parent?
The Child's foreign key will be null, so the link is broken in the database. Execution_table step 5 shows saving with correct links only if Child.parent is set.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what database operations occur?
AInsert Child only, Parent is not saved
BInsert Parent and Child with foreign key linking Child to Parent
COnly insert Parent, Child is not saved
DNo database operations happen
💡 Hint
Check the 'Database Operation' column at step 5 in execution_table
At which step does Parent.children first contain Child1?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Parent.children' column in execution_table rows
If Child1.parent was never set, what would Parent.children contain after saving?
AParent.children would be empty
BChild1 would still be in Parent.children
CParent.children would contain null
DParent.children would cause an error
💡 Hint
Refer to key_moments about relationship ownership and execution_table step 5
Concept Snapshot
@OneToMany links one parent to many children.
Child owns the relationship with @ManyToOne.
Set Child.parent before adding to Parent.children.
Saving Parent cascades to save Children.
Retrieving Parent loads all Children.
This keeps DB foreign keys consistent.
Full Transcript
The @OneToMany relationship in Spring Boot connects one parent entity to many child entities. The parent class has a collection annotated with @OneToMany, and the child class has a reference back to the parent annotated with @ManyToOne. The child side owns the relationship, so setting the child's parent reference is essential before adding the child to the parent's collection. When saving the parent, Spring Boot saves both parent and children, linking them in the database with foreign keys. Retrieving the parent loads all its children automatically. This ensures data consistency and proper linkage between entities.

Practice

(1/5)
1. What does the @OneToMany annotation represent in Spring Boot JPA?
easy
A. A relationship where one entity is linked to many entities
B. A relationship where many entities are linked to one entity
C. A way to delete entities automatically
D. A method to fetch data lazily

Solution

  1. Step 1: Understand the meaning of @OneToMany

    The annotation defines a connection where one object relates to multiple objects, like one author having many books.
  2. Step 2: Differentiate from other relationships

    @ManyToOne is the opposite, linking many entities to one. @OneToMany specifically means one to many.
  3. Final Answer:

    A relationship where one entity is linked to many entities -> Option A
  4. Quick Check:

    @OneToMany = one to many link [OK]
Hint: Think 'one' object owns 'many' related objects [OK]
Common Mistakes:
  • Confusing @OneToMany with @ManyToOne
  • Thinking it deletes entities automatically
  • Assuming it controls fetch type only
2. Which of the following is the correct way to declare a @OneToMany relationship in an entity class?
easy
A. @OneToMany(mappedBy = "parent") private List<Child> children;
B. @OneToMany private Child child;
C. @OneToMany(mappedBy = "children") private Child parent;
D. @OneToMany private Map childrenMap;

Solution

  1. Step 1: Check the collection type for @OneToMany

    @OneToMany requires a collection like List or Set to hold multiple related entities, so List<Child> is correct.
  2. Step 2: Verify the mappedBy attribute usage

    mappedBy should point to the field name in the Child entity that owns the relationship, here "parent" is correct.
  3. Final Answer:

    @OneToMany(mappedBy = "parent") private List<Child> children; -> Option A
  4. Quick Check:

    Use collection + mappedBy for correct syntax [OK]
Hint: Use a collection and mappedBy to link entities [OK]
Common Mistakes:
  • Using single object instead of collection
  • Wrong mappedBy value
  • Using Map instead of List or Set
3. Given the following code snippet, what will be the output when fetching a Department entity?
@Entity
public class Department {
  @Id
  private Long id;

  @OneToMany(mappedBy = "department", fetch = FetchType.EAGER)
  private List<Employee> employees;

  // getters and setters
}

Assuming the department has 3 employees, what happens when you load the department?
medium
A. Only one employee is loaded due to default limit
B. The department loads without employees until accessed
C. The department loads with all 3 employees immediately
D. An error occurs because fetch type is invalid

Solution

  1. Step 1: Understand fetch type EAGER

    FetchType.EAGER means related entities are loaded immediately with the main entity.
  2. Step 2: Apply to the employees list

    Since employees are marked EAGER, all 3 employees will be loaded when the department is fetched.
  3. Final Answer:

    The department loads with all 3 employees immediately -> Option C
  4. Quick Check:

    FetchType.EAGER loads related entities immediately [OK]
Hint: EAGER fetch loads all related data immediately [OK]
Common Mistakes:
  • Confusing EAGER with LAZY fetch
  • Assuming default fetch loads lazily
  • Expecting errors from fetch type
4. Identify the error in this @OneToMany mapping:
@Entity
public class Order {
  @Id
  private Long id;

  @OneToMany
  private List<Item> items;

  // getters and setters
}

Why might this cause issues when saving an Order with Items?

medium
A. List<Item> should be Set<Item> for @OneToMany
B. Missing mappedBy causes owning side confusion
C. The @Id annotation is missing
D. Items should be annotated with @ManyToMany

Solution

  1. Step 1: Check ownership in bidirectional @OneToMany

    Without mappedBy, JPA doesn't know which side owns the relationship, causing extra join tables or errors.
  2. Step 2: Understand impact on saving

    Without ownership, saving Order and Items may not link properly, causing data inconsistency.
  3. Final Answer:

    Missing mappedBy causes owning side confusion -> Option B
  4. Quick Check:

    mappedBy defines owner, missing it causes issues [OK]
Hint: Always set mappedBy on non-owning side [OK]
Common Mistakes:
  • Omitting mappedBy in bidirectional relationships
  • Confusing collection types for @OneToMany
  • Misusing @ManyToMany instead of @OneToMany
5. You want to delete a Category and all its related Product entities automatically. Which @OneToMany configuration achieves this behavior?
hard
A. @OneToMany(cascade = CascadeType.PERSIST) private List<Product> products;
B. @OneToMany(mappedBy = "category") private List<Product> products;
C. @OneToMany(fetch = FetchType.LAZY) private List<Product> products;
D. @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) private List<Product> products;

Solution

  1. Step 1: Understand cascade and orphanRemoval

    CascadeType.ALL applies all operations including delete to related entities. orphanRemoval=true removes child entities if removed from parent.
  2. Step 2: Apply to deleting Category

    With cascade ALL and orphanRemoval, deleting Category deletes all linked Products automatically.
  3. Final Answer:

    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) private List<Product> products; -> Option D
  4. Quick Check:

    Use cascade ALL + orphanRemoval for auto-delete [OK]
Hint: Cascade ALL + orphanRemoval deletes children automatically [OK]
Common Mistakes:
  • Forgetting cascade causes children to remain
  • Using only cascade PERSIST won't delete children
  • Ignoring orphanRemoval for child removal