Bird
Raised Fist0
Spring Bootframework~20 mins

@ManyToOne 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 @ManyToOne Relationships
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this @ManyToOne mapping when fetching a child entity?

Given the following JPA entities, what will be printed when fetching a Book entity and accessing its author field?

Spring Boot
import jakarta.persistence.*;

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // getters and setters
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // getters and setters
}

// In a service method:
Book book = entityManager.find(Book.class, 1L);
System.out.println(book.getAuthor().getName());
APrints null because the author is not fetched automatically
BPrints the name of the author linked to the book with id 1
CThrows NullPointerException because author is not initialized
DThrows a compilation error due to missing annotations
Attempts:
2 left
💡 Hint

Consider the default fetch type of @ManyToOne and what happens when you access the related entity.

📝 Syntax
intermediate
1:30remaining
Which option correctly defines a @ManyToOne relationship with a custom join column?

Choose the correct code snippet that defines a @ManyToOne relationship with a join column named category_id in a Product entity.

A
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
B
@ManyToOne
@JoinColumn("category_id")
private Category category;
C
@ManyToOne
@JoinColumn(columnName = "category_id")
private Category category;
D
@ManyToOne
@JoinColumn(name = category_id)
private Category category;
Attempts:
2 left
💡 Hint

Remember the correct attribute name for specifying the column name in @JoinColumn.

🔧 Debug
advanced
2:30remaining
Why does this @ManyToOne mapping cause a runtime LazyInitializationException?

Consider this code snippet:

Book book = entityManager.find(Book.class, 1L);
entityManager.close();
System.out.println(book.getAuthor().getName());

Why does accessing book.getAuthor().getName() throw a LazyInitializationException?

ABecause the default fetch type of @ManyToOne is LAZY and the entity manager is closed before accessing the author
BBecause the Book entity is detached and cannot access any fields
CBecause the @JoinColumn is missing, so the relationship is not mapped
DBecause the author field is null and accessing getName() causes the exception
Attempts:
2 left
💡 Hint

Check the default fetch type of @ManyToOne and when the related entity is loaded.

state_output
advanced
2:30remaining
What is the state of the owning side after this code runs?

Given these entities:

@Entity
class Order {
  @Id
  Long id;

  @ManyToOne
  Customer customer;
}

@Entity
class Customer {
  @Id
  Long id;

  String name;
}

And this code:

Order order = new Order();
Customer customer = new Customer();
customer.setName("Alice");
order.setCustomer(customer);
entityManager.persist(customer);
entityManager.persist(order);
entityManager.flush();

What is true about the database state after flush?

AOrder is saved but customer_id in Order is null because Customer has no id yet
BOnly Customer is saved because Order depends on Customer but is not persisted
CNeither entity is saved because Customer must be saved before setting in Order
DBoth Customer and Order are saved, and Order's customer_id column references the Customer's id
Attempts:
2 left
💡 Hint

Think about the order of persisting and how JPA handles relationships.

🧠 Conceptual
expert
3:00remaining
Which statement about @ManyToOne and cascading is correct?

Consider a @ManyToOne relationship from Invoice to Client. Which of these statements about cascading operations is true?

ACascadeType.REMOVE on @ManyToOne deletes the Invoice when Client is deleted
BCascadeType.ALL on @ManyToOne is required to save the Client when saving Invoice
CCascadeType.ALL on @ManyToOne causes operations on Invoice to propagate to Client, which can lead to unintended deletes
DCascadeType.PERSIST on @ManyToOne prevents saving Invoice without an existing Client
Attempts:
2 left
💡 Hint

Think about the direction of cascading and what happens when you delete the owning entity.

Practice

(1/5)
1. What does the @ManyToOne annotation represent in Spring Boot JPA?
easy
A. A many-to-one relationship where many entities link to one entity
B. A one-to-many relationship where one entity links to many entities
C. A one-to-one relationship between two entities
D. A many-to-many relationship between two entities

Solution

  1. Step 1: Understand relationship types in JPA

    @ManyToOne means many instances of an entity relate to one instance of another entity.
  2. Step 2: Match the description to the annotation

    The annotation @ManyToOne specifically defines many entities pointing to one entity.
  3. Final Answer:

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

    @ManyToOne = many entities to one entity [OK]
Hint: Remember: Many objects point to one with @ManyToOne [OK]
Common Mistakes:
  • Confusing @ManyToOne with @OneToMany
  • Thinking it means one-to-one
  • Mixing it up with many-to-many
2. Which of the following is the correct way to declare a @ManyToOne relationship with a join column named category_id?
easy
A. @ManyToOne @JoinColumn(name = "category_id") private Category category;
B. @OneToMany @JoinColumn(name = "category_id") private Category category;
C. @ManyToOne @JoinColumn(columnName = "category_id") private Category category;
D. @ManyToOne @JoinColumn(name = category_id) private Category category;

Solution

  1. Step 1: Check correct annotation usage

    The relationship is many-to-one, so @ManyToOne is correct.
  2. Step 2: Verify @JoinColumn syntax

    The attribute to specify column name is name and the value must be a string in quotes.
  3. Final Answer:

    @ManyToOne @JoinColumn(name = "category_id") private Category category; -> Option A
  4. Quick Check:

    @JoinColumn uses name="column_name" [OK]
Hint: Use @JoinColumn(name = "column_name") with quotes [OK]
Common Mistakes:
  • Using @OneToMany instead of @ManyToOne
  • Using columnName instead of name in @JoinColumn
  • Omitting quotes around column name
3. Given the entities below, what will be the output of System.out.println(order.getCustomer().getName()); if the order is linked to a customer named "Alice"?
public class Order {
  @ManyToOne
  @JoinColumn(name = "customer_id")
  private Customer customer;

  public Customer getCustomer() { return customer; }
}

public class Customer {
  private String name;
  public String getName() { return name; }
}
medium
A. Compilation error
B. customer_id
C. null
D. Alice

Solution

  1. Step 1: Understand the relationship and method calls

    The order has a customer linked via @ManyToOne, so calling getCustomer() returns the Customer object.
  2. Step 2: Access the customer's name

    Calling getName() on the Customer returns the customer's name, which is "Alice".
  3. Final Answer:

    Alice -> Option D
  4. Quick Check:

    order.getCustomer().getName() = "Alice" [OK]
Hint: Follow the chain: order -> customer -> name [OK]
Common Mistakes:
  • Expecting the join column name instead of customer name
  • Assuming null if not initialized
  • Thinking it causes a compile error
4. Identify the error in the following code snippet that uses @ManyToOne:
@Entity
public class Book {
  @Id
  private Long id;
  @ManyToOne
  @JoinColumn(name = "author_id")
  private Author author;

  public Author getAuthor() { return author; }
  public void setAuthor(Author author) { this.author = author; }
}

@Entity
public class Author {
  private String name;
  public String getName() { return name; }
}
medium
A. Author class is missing @Entity annotation
B. Book class should use @OneToMany instead of @ManyToOne
C. Missing @Id annotation in Author class
D. Join column name should be "authorId" not "author_id"

Solution

  1. Step 1: Check entity requirements

    Every JPA entity must have a primary key annotated with @Id. The Author class lacks this.
  2. Step 2: Verify other annotations

    Author has @Entity but no @Id, which will cause runtime errors.
  3. Final Answer:

    Missing @Id annotation in Author class -> Option C
  4. Quick Check:

    Entity requires @Id field [OK]
Hint: Always add @Id to every entity class [OK]
Common Mistakes:
  • Confusing relationship annotations
  • Ignoring missing primary key
  • Assuming join column naming causes error
5. You have two entities: Order and Customer. Each order belongs to one customer, but a customer can have many orders. You want to fetch all orders with their customers efficiently. Which approach correctly uses @ManyToOne for eager loading?
hard
A. Use @ManyToOne(fetch = FetchType.LAZY) on Order's customer and fetch customers separately
B. Use @ManyToOne(fetch = FetchType.EAGER) on Order's customer to load customers with orders
C. Use @OneToMany(fetch = FetchType.EAGER) on Customer's orders and no mapping on Order
D. Use @ManyToOne without fetch type and manually query customers for each order

Solution

  1. Step 1: Understand fetch types in @ManyToOne

    By default, @ManyToOne uses FetchType.EAGER, loading the related customer eagerly with the order.
  2. Step 2: Match the best approach

    Explicitly using fetch = FetchType.EAGER on the Order's customer field ensures efficient eager loading for this many-to-one relationship.
  3. Final Answer:

    Use @ManyToOne(fetch = FetchType.EAGER) on Order's customer to load customers with orders -> Option B
  4. Quick Check:

    @ManyToOne = EAGER by default [OK]
Hint: EAGER fetch on @ManyToOne loads related data together [OK]
Common Mistakes:
  • Using LAZY fetch without proper query optimization
  • Using @OneToMany on Customer without Order mapping
  • Manually querying related entities inefficiently