1. Concept library
  2. Java & Spring Boot
  3. Module 8: Data access with JPA

Concept

Relationships

@OneToMany, @ManyToOne and @ManyToMany map foreign keys to object references. How they are fetched, lazily or eagerly, decides how many queries a page load makes.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what @OneToMany and @ManyToOne map
  2. Explain lazy and eager fetching and their effect on the query count
  3. Spot the N+1 query problem and fix it with a fetch join

In practice

A few lines that show Relationships doing its job.

Java
@Entity
public class Order {
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<LineItem> items = new ArrayList<>();
}

@Entity
public class LineItem {
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Order order;
}

// Loading 50 orders with their items in one query:
@Query("select o from Order o join fetch o.items where o.status = :status")
List<Order> findWithItems(OrderStatus status);

The common mistake

Watch for

The N+1 query problem: load a list of orders, then touch order.getItems() in a loop, and each one fires its own query. Fetch the relationship in the query that loads the list.

What to know first

Your roadmap puts these before Relationships, unless you already know them.

How it stays learned

Once a session shows you understand Relationships, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Entities and repositories
Next in the moduleTransactions →