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
Create a @OneToMany Relationship in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage a library. Each Author can write many Books. You need to set up the data model to reflect this relationship.
🎯 Goal: Build two Java entity classes, Author and Book, where one author can have many books using the @OneToMany annotation in Spring Boot.
📋 What You'll Learn
Create an Author entity class with an id and name field
Create a Book entity class with an id, title, and a reference to Author
Add a @OneToMany relationship in Author to hold multiple Book objects
Add a @ManyToOne relationship in Book to link back to Author
💡 Why This Matters
🌍 Real World
Managing related data in applications like libraries, stores, or blogs where one entity owns many related entities.
💼 Career
Understanding and implementing JPA relationships is essential for backend developers working with Spring Boot and databases.
Progress0 / 4 steps
1
Create the Author entity class
Create a Java class called Author annotated with @Entity. Add a private Long id field annotated with @Id and @GeneratedValue. Add a private String name field. Include standard getters and setters.
Spring Boot
Hint
Use @Entity on the class. Use @Id and @GeneratedValue on the id field.
2
Create the Book entity class with author reference
Create a Java class called Book annotated with @Entity. Add a private Long id field annotated with @Id and @GeneratedValue. Add a private String title field. Add a private Author author field annotated with @ManyToOne. Include standard getters and setters.
Spring Boot
Hint
Use @ManyToOne on the author field to link back to Author.
3
Add @OneToMany relationship in Author
In the Author class, add a private List<Book> books field annotated with @OneToMany(mappedBy = "author"). Initialize it with new ArrayList<>(). Add standard getter and setter for books. Import necessary classes.
Spring Boot
Hint
Use @OneToMany(mappedBy = "author") on the books field. Initialize it with new ArrayList<>().
4
Complete the entity classes with imports and annotations
Ensure both Author and Book classes have all necessary imports for JPA annotations and collections. Confirm @Entity is present on both classes. Confirm @Id, @GeneratedValue, @OneToMany(mappedBy = "author"), and @ManyToOne annotations are correctly placed.
Spring Boot
Hint
Check that all imports and annotations are present and correctly placed in both classes.
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
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.
Step 2: Differentiate from other relationships
@ManyToOne is the opposite, linking many entities to one. @OneToMany specifically means one to many.
Final Answer:
A relationship where one entity is linked to many entities -> Option A
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
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.
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.
Final Answer:
@OneToMany(mappedBy = "parent") private List<Child> children; -> Option A
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
Step 1: Understand fetch type EAGER
FetchType.EAGER means related entities are loaded immediately with the main entity.
Step 2: Apply to the employees list
Since employees are marked EAGER, all 3 employees will be loaded when the department is fetched.
Final Answer:
The department loads with all 3 employees immediately -> Option C
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
Step 1: Check ownership in bidirectional @OneToMany
Without mappedBy, JPA doesn't know which side owns the relationship, causing extra join tables or errors.
Step 2: Understand impact on saving
Without ownership, saving Order and Items may not link properly, causing data inconsistency.
Final Answer:
Missing mappedBy causes owning side confusion -> Option B
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;