Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →
TOPIC 2 OF 5 · 2 MIN READ

Relationships, Lazy vs Eager Loading and LazyInitializationException

Mapping @OneToMany, @ManyToOne and @ManyToMany correctly, and choosing lazy or eager fetching, decides most JPA performance. LazyInitializationException is the error every Spring developer meets, and interviewers ask why it happens.

What you will learn

  • Map bidirectional relationships with mappedBy
  • Know the default fetch types
  • Explain LazyInitializationException
  • Use cascade and orphanRemoval carefully

Key concepts

Owning side

The side with the foreign key (@ManyToOne, or the side without mappedBy) controls the column. mappedBy marks the inverse side. Keep both sides in sync with helper methods.

Default fetch

@ManyToOne and @OneToOne are EAGER by default; @OneToMany and @ManyToMany are LAZY. Best practice: make everything LAZY and fetch what each use case needs.

LazyInitializationException

Accessing a lazy association after the persistence context closed (outside the transaction, for example while serialising in the controller). Fix by fetching it in the query or mapping to DTOs inside the transaction, not by enabling open-in-view or making it eager.

Cascade

CascadeType.PERSIST / MERGE / REMOVE / ALL passes operations from parent to children. Use it on true parent-child aggregates (order → items), never on @ManyToOne to shared entities.

Step by step

Parent and children

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

    public void addItem(OrderItem item) { items.add(item); item.setOrder(this); }
    public void removeItem(OrderItem item) { items.remove(item); item.setOrder(null); }
}

@Entity
class OrderItem {
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "order_id")
    private Order order;
}

Examples

Open Session in View

# Spring Boot enables it by default and logs a warning.
# It keeps the session open during view rendering, hiding lazy loading in controllers
# and holding a DB connection for the whole request. Turn it off:
spring.jpa.open-in-view=false

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Model users and roles as @ManyToMany, then refactor to a join entity with an assignedAt column.
  • Reproduce LazyInitializationException and fix it with a fetch join.

Interview questions

What interviewers ask next on this topic. Answer out loud first, then open the model answer.

Why avoid EAGER fetching?

It loads associations every time the entity is loaded, even when not needed, often with extra queries (N+1 for collections of entities with eager parents), and you cannot turn it off per query. LAZY plus explicit fetching per use case is predictable.

List or Set for @OneToMany?

Set avoids duplicates and Hibernate's "bag" quirks (fetching two bags at once throws MultipleBagFetchException), but needs good equals and hashCode. List keeps order and is common; just do not fetch-join two lists in one query.

Summary

Make associations LAZY, keep both sides of bidirectional relations in sync, cascade only within aggregates, disable open-in-view, and fetch what each use case needs inside the transaction.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus