Bird
Raised Fist0
Spring Bootframework~20 mins

@OneToMany relationship in Spring Boot - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Master of @OneToMany Relationships
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when fetching a parent entity with @OneToMany lazy loading?

Consider a Spring Boot JPA entity Author with a @OneToMany relationship to Book marked as fetch = FetchType.LAZY. When you fetch an Author from the database and access the list of Book entities for the first time, what happens?

Spring Boot
public class Author {
    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
    private List<Book> books;

    // getters and setters
}

// In service:
Author author = authorRepository.findById(1L).get();
List<Book> books = author.getBooks();
AThe list of books is always empty unless explicitly fetched with a separate query.
BThe list of books is fetched immediately when the author is fetched, regardless of getBooks() call.
CAn exception is thrown because lazy loading is not supported in Spring Boot.
DThe list of books is fetched from the database only when getBooks() is called for the first time.
Attempts:
2 left
💡 Hint

Think about what FetchType.LAZY means for loading related entities.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly defines a bidirectional @OneToMany relationship?

Choose the correct way to define a bidirectional @OneToMany relationship between Author and Book entities in Spring Boot JPA.

AIn Author: <code>@OneToMany private List<Book> books;</code><br>In Book: <code>@ManyToOne(mappedBy = "author") private Author author;</code>
BIn Author: <code>@ManyToOne private List<Book> books;</code><br>In Book: <code>@OneToMany private Author author;</code>
CIn Author: <code>@OneToMany(mappedBy = "author") private List<Book> books;</code><br>In Book: <code>@ManyToOne private Author author;</code>
DIn Author: <code>@OneToMany(mappedBy = "books") private List<Book> books;</code><br>In Book: <code>@ManyToOne private Author author;</code>
Attempts:
2 left
💡 Hint

Remember that mappedBy is used on the inverse side to point to the owning side's field.

🔧 Debug
advanced
2:00remaining
Why does adding a new Book to Author's list not persist the relationship?

Given the following code, why does adding a new Book to the Author's books list not save the relationship in the database?

Author author = authorRepository.findById(1L).get();
Book newBook = new Book();
newBook.setTitle("New Book");
author.getBooks().add(newBook);
authorRepository.save(author);
ABecause the <code>Book</code> entity's <code>author</code> field is not set, so JPA does not know about the relationship.
BBecause <code>authorRepository.save()</code> does not cascade saves to the <code>books</code> list by default.
CBecause the <code>Author</code> entity must be deleted before adding new books.
DBecause the <code>books</code> list is immutable and cannot be modified.
Attempts:
2 left
💡 Hint

Think about which side owns the relationship and what fields must be set for JPA to persist it.

state_output
advanced
2:00remaining
What is the size of the books list after this code runs?

Given the following entities and code, what is the size of author.getBooks() after execution?

@Entity
class Author {
  @OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
  private List books = new ArrayList<>();
}

@Entity
class Book {
  @ManyToOne
  private Author author;
}

// Code:
Author author = new Author();
Book book1 = new Book();
book1.setAuthor(author);
Book book2 = new Book();
// book2.setAuthor(author); // missing

author.getBooks().add(book1);
author.getBooks().add(book2);

int size = author.getBooks().size();
A2
B1
C0
DThrows NullPointerException
Attempts:
2 left
💡 Hint

Consider what the books list contains after adding both books.

🧠 Conceptual
expert
2:00remaining
What is the effect of omitting 'mappedBy' in a @OneToMany relationship?

In a Spring Boot JPA entity, what happens if you define a @OneToMany relationship without specifying the mappedBy attribute?

AJPA throws a runtime exception because <code>mappedBy</code> is mandatory for @OneToMany.
BJPA creates a join table to manage the relationship instead of using a foreign key in the child table.
CThe relationship is ignored and no database mapping is created.
DJPA treats the relationship as unidirectional and uses the foreign key in the child table automatically.
Attempts:
2 left
💡 Hint

Think about how JPA manages ownership of relationships and what happens without mappedBy.

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