Bird
Raised Fist0
Spring Bootframework~20 mins

Why relationships matter in JPA in Spring Boot - Challenge Your Understanding

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
🎖️
JPA Relationship Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when you fetch a OneToMany relationship lazily in JPA?

Consider a JPA entity Author with a @OneToMany relationship to Book marked as fetch = FetchType.LAZY. What will happen when you access the books collection outside a transaction?

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

    // getters and setters
}

// In a service method without transaction
Author author = authorRepository.findById(1L).orElseThrow();
List<Book> books = author.getBooks(); // What happens here?
AThe code compiles but returns an empty list always.
BA LazyInitializationException is thrown because the collection is accessed outside the transaction.
CThe books collection is null because it was not fetched eagerly.
DThe books collection is fully loaded automatically without any error.
Attempts:
2 left
💡 Hint

Think about how lazy loading works and when the database session is active.

📝 Syntax
intermediate
2:00remaining
Which annotation correctly defines a bidirectional ManyToOne/OneToMany relationship in JPA?

Given two entities Order and OrderItem, which option correctly sets up a bidirectional relationship where one order has many order items?

Spring Boot
public class Order {
    // relationship here
}

public class OrderItem {
    // relationship here
}
A
@ManyToOne(mappedBy = "items") private Order order; // in Order
@OneToMany @JoinColumn(name = "order_id") private List&lt;OrderItem&gt; items; // in OrderItem
B
@OneToMany private List&lt;OrderItem&gt; items; // in Order
@ManyToOne(mappedBy = "order") private Order order; // in OrderItem
C
@OneToMany(mappedBy = "order") private List&lt;OrderItem&gt; items; // in Order
@ManyToOne @JoinColumn(name = "order_id") private Order order; // in OrderItem
D
@ManyToOne private Order order; // in Order
@OneToMany(mappedBy = "order") private List&lt;OrderItem&gt; items; // in OrderItem
Attempts:
2 left
💡 Hint

Remember that mappedBy goes on the inverse side and @JoinColumn on the owning side.

state_output
advanced
2:00remaining
What is the state of entities after cascading a persist in a OneToMany relationship?

Given an Author entity with a @OneToMany(cascade = CascadeType.PERSIST) relationship to Book, what happens when you persist the author with new books added?

Spring Boot
Author author = new Author();
author.setName("Jane Doe");
Book book1 = new Book();
book1.setTitle("Book One");
Book book2 = new Book();
book2.setTitle("Book Two");
author.setBooks(List.of(book1, book2));
entityManager.persist(author);
// What is the state of book1 and book2 after this?
ABoth book1 and book2 are also persisted automatically due to cascade persist.
BOnly author is persisted; book1 and book2 remain transient and not saved.
CBooks are persisted but without their relationship to author set.
DPersisting author throws an exception because books are not explicitly persisted.
Attempts:
2 left
💡 Hint

Think about what cascade persist means for related entities.

🔧 Debug
advanced
2:00remaining
Why does this bidirectional relationship cause infinite recursion in JSON serialization?

Given these entities with bidirectional relationships, serializing Author to JSON causes infinite recursion. Why?

Spring Boot
public class Author {
    @OneToMany(mappedBy = "author")
    private List<Book> books;
    // getters and setters
}

public class Book {
    @ManyToOne
    private Author author;
    // getters and setters
}

// Serialization code:
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(author);
ABecause the Book entity lacks a primary key, causing serialization to fail.
BBecause the @OneToMany annotation is missing fetch type, causing serialization failure.
CBecause the ObjectMapper is not configured to handle collections, causing an error.
DBecause Author references Book and Book references Author, causing infinite back-and-forth serialization.
Attempts:
2 left
💡 Hint

Think about how JSON serialization handles circular references.

🧠 Conceptual
expert
2:00remaining
Why is it important to define owning and inverse sides in JPA relationships?

In JPA, relationships have owning and inverse sides. Why does this distinction matter?

ABecause only the owning side controls the database foreign key updates, preventing inconsistent data.
BBecause the inverse side is the only one that can cascade operations to related entities.
CBecause the owning side is ignored during persistence, and only the inverse side is saved.
DBecause both sides independently update the database, causing duplicate foreign keys.
Attempts:
2 left
💡 Hint

Consider which side JPA uses to manage the foreign key column in the database.

Practice

(1/5)
1. Why are relationships important in JPA when working with entities?
easy
A. They allow easy navigation and management of related data between entities.
B. They improve the speed of the Java compiler.
C. They automatically generate user interfaces for entities.
D. They replace the need for database tables.

Solution

  1. Step 1: Understand the role of relationships in JPA

    Relationships link entities so you can access related data easily, like a map connecting places.
  2. Step 2: Recognize the benefit of these links

    They help manage and query related data without manual joins or extra queries.
  3. Final Answer:

    They allow easy navigation and management of related data between entities. -> Option A
  4. Quick Check:

    Relationships = Easy data navigation [OK]
Hint: Think of relationships as bridges connecting data [OK]
Common Mistakes:
  • Confusing relationships with UI features
  • Assuming relationships speed up compilation
  • Believing relationships remove database tables
2. Which annotation correctly defines a many-to-one relationship in JPA?
easy
A. @OneToMany
B. @ManyToMany
C. @ManyToOne
D. @OneToOne

Solution

  1. Step 1: Recall JPA relationship annotations

    @ManyToOne is used when many entities relate to one entity, like many orders to one customer.
  2. Step 2: Match the annotation to the relationship type

    @ManyToOne fits the question, others represent different relationships.
  3. Final Answer:

    @ManyToOne -> Option C
  4. Quick Check:

    @ManyToOne = many to one link [OK]
Hint: Many to one? Use @ManyToOne annotation [OK]
Common Mistakes:
  • Using @OneToMany instead of @ManyToOne
  • Confusing @OneToOne with many-to-one
  • Mixing up @ManyToMany for simple many-to-one
3. Given the following JPA entities, what will be the output when fetching a Book and accessing its author.getName()?
@Entity
class Book {
  @Id
  Long id;
  String title;
  @ManyToOne
  Author author;
}

@Entity
class Author {
  @Id
  Long id;
  String name;
}
medium
A. NullPointerException because author is not initialized.
B. A compilation error due to missing @JoinColumn annotation.
C. The book's title will be returned instead of the author's name.
D. The author's name linked to the book will be returned.

Solution

  1. Step 1: Understand the @ManyToOne relationship

    The Book entity has a many-to-one link to Author, so each book has one author object.
  2. Step 2: Accessing author.getName()

    When fetching a Book, JPA loads the linked Author, so calling getName() returns the author's name.
  3. Final Answer:

    The author's name linked to the book will be returned. -> Option D
  4. Quick Check:

    Book.author.getName() = Author's name [OK]
Hint: ManyToOne means book has one author object [OK]
Common Mistakes:
  • Assuming missing @JoinColumn causes compile error
  • Expecting NullPointerException without checking data
  • Confusing book title with author name
4. Identify the error in this JPA relationship mapping:
@Entity
class Order {
  @Id
  Long id;
  @OneToMany
  Customer customer;
}
medium
A. Using @OneToMany on a single Customer field instead of a collection.
B. Missing @Id annotation on Customer entity.
C. Order entity should not have any relationships.
D. The @OneToMany annotation should be replaced with @ManyToOne.

Solution

  1. Step 1: Check the @OneToMany usage

    @OneToMany expects a collection (like List or Set), not a single object.
  2. Step 2: Identify the field type mismatch

    The field 'customer' is a single Customer, so @OneToMany is incorrect here.
  3. Final Answer:

    Using @OneToMany on a single Customer field instead of a collection. -> Option A
  4. Quick Check:

    @OneToMany needs collection, not single object [OK]
Hint: @OneToMany always needs a collection type [OK]
Common Mistakes:
  • Applying @OneToMany to a single entity field
  • Ignoring collection requirement for @OneToMany
  • Confusing relationship direction annotations
5. You have two entities: Student and Course. A student can enroll in many courses, and a course can have many students. Which JPA relationship setup correctly models this, and why is it important to define it properly?
hard
A. Use @OneToMany on Student and @ManyToOne on Course; it simplifies the database schema.
B. Use @ManyToMany on both sides with a join table; it ensures proper linking and querying of students and courses.
C. Use @OneToOne on both entities; it guarantees unique pairs.
D. No relationship annotations needed; just store IDs manually.

Solution

  1. Step 1: Identify the relationship type

    Many students can enroll in many courses, so the relationship is many-to-many.
  2. Step 2: Choose correct annotations and explain importance

    @ManyToMany on both sides with a join table models this correctly, allowing JPA to manage links and queries efficiently.
  3. Final Answer:

    Use @ManyToMany on both sides with a join table; it ensures proper linking and querying of students and courses. -> Option B
  4. Quick Check:

    Many-to-many needs @ManyToMany with join table [OK]
Hint: Many-to-many? Use @ManyToMany with join table [OK]
Common Mistakes:
  • Using one-to-many for many-to-many relationships
  • Skipping relationship annotations and managing IDs manually
  • Using one-to-one where many-to-many is needed