Bird
Raised Fist0
Spring Bootframework~10 mins

Fetch types (LAZY vs EAGER) in Spring Boot - Visual Side-by-Side Comparison

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
Concept Flow - Fetch types (LAZY vs EAGER)
Start Entity Load
Fetch Type?
EAGERLoad Related Data Immediately
Load Proxy Placeholder
Access Related Data?
NoReturn Proxy
Yes
Fetch Related Data Now
Return Full Data
When loading an entity, eager fetch loads related data immediately, while lazy fetch loads a placeholder and fetches related data only when accessed.
Execution Sample
Spring Boot
class Order {
  @OneToMany(fetch = FetchType.LAZY)
  List<Item> items;
}

Order order = repo.findById(1).orElse(null);
order.getItems();
This code loads an Order entity with items fetched lazily, so items load only when getItems() is called.
Execution Table
StepActionFetch TypeData LoadedResult
1Load Order entityLAZYOrder data onlyOrder object with items proxy
2Access order.getItems()LAZYItems data fetched nowFull Order with items loaded
3Load Order entityEAGEROrder and items dataFull Order with items loaded immediately
4Access order.getItems()EAGERNo additional fetchItems already loaded
💡 Execution stops after data is fully loaded or proxy returned depending on fetch type.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
ordernullOrder with items proxyOrder with items loadedOrder with items loadedOrder with items loaded
Key Moments - 2 Insights
Why does accessing items trigger a database call in LAZY fetch?
Because at Step 1 in execution_table, only a proxy is loaded. The actual items data is fetched only when getItems() is called at Step 2.
Does EAGER fetch load related data immediately or later?
EAGER fetch loads related data immediately as shown in Step 3, so no extra fetch happens when accessing items at Step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is loaded at Step 1 with LAZY fetch?
AOrder data only with items proxy
BOrder and items data fully loaded
COnly items data loaded
DNo data loaded yet
💡 Hint
Check Step 1 row under Data Loaded column in execution_table.
At which step does the actual items data load in LAZY fetch?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at when 'Items data fetched now' happens in execution_table.
If fetch type changes from LAZY to EAGER, what changes in the execution?
AItems load only when accessed at Step 2
BItems load immediately with Order at Step 3
COrder does not load at all
DItems never load
💡 Hint
Compare Step 3 and Step 1 rows for EAGER vs LAZY in execution_table.
Concept Snapshot
Fetch Types in Spring Boot:
- LAZY: Load main entity first, related data loads only on access.
- EAGER: Load main entity and related data immediately.
- LAZY uses proxy placeholders to delay loading.
- EAGER fetch can impact performance if related data is large.
- Choose fetch type based on use case to optimize loading.
Full Transcript
In Spring Boot, fetch types control when related data loads with an entity. EAGER fetch loads all related data immediately when the main entity loads. LAZY fetch loads only the main entity first and uses a proxy for related data. The related data loads only when accessed later. This helps optimize performance by delaying data loading until needed. The execution table shows that with LAZY, the items list is a proxy after loading the order, and only fetches items when getItems() is called. With EAGER, items load immediately with the order. Understanding this helps avoid unexpected database calls and performance issues.

Practice

(1/5)
1. What does the LAZY fetch type do in Spring Boot JPA?
easy
A. It disables loading of related entities completely.
B. It loads all related entities immediately with the main entity.
C. It delays loading related entities until they are accessed.
D. It loads related entities only during application startup.

Solution

  1. Step 1: Understand fetch types in JPA

    Fetch types control when related data is loaded from the database.
  2. Step 2: Define LAZY fetch behavior

    LAZY means related entities are loaded only when you access them, not immediately.
  3. Final Answer:

    It delays loading related entities until they are accessed. -> Option C
  4. Quick Check:

    LAZY = delayed loading [OK]
Hint: LAZY means wait to load until needed [OK]
Common Mistakes:
  • Confusing LAZY with EAGER loading
  • Thinking LAZY loads data immediately
  • Assuming LAZY disables loading
2. Which is the correct way to specify EAGER fetching on a JPA relationship in Spring Boot?
easy
A. @ManyToOne(fetch = FetchType.EAGER)
B. @OneToMany(fetch = FetchType.LAZY)
C. @OneToOne(fetch = FetchType.LAZY)
D. @ManyToMany(fetch = FetchType.LAZY)

Solution

  1. Step 1: Identify correct annotation and fetch type

    EAGER fetch type is set using fetch = FetchType.EAGER inside relationship annotations.
  2. Step 2: Match correct relationship and fetch type

    @ManyToOne(fetch = FetchType.EAGER) uses @ManyToOne(fetch = FetchType.EAGER), which is valid and correct.
  3. Final Answer:

    @ManyToOne(fetch = FetchType.EAGER) -> Option A
  4. Quick Check:

    EAGER fetch uses FetchType.EAGER [OK]
Hint: EAGER fetch uses FetchType.EAGER in annotation [OK]
Common Mistakes:
  • Using LAZY instead of EAGER for eager loading
  • Mixing relationship types with wrong fetch types
  • Forgetting to specify fetch attribute
3. Given the following code snippet, what will happen when order.getItems() is called if items is marked with fetch = FetchType.LAZY?
@Entity
class Order {
  @OneToMany(fetch = FetchType.LAZY)
  private List<Item> items;
}
Order order = entityManager.find(Order.class, 1L);
// No call to getItems() yet
medium
A. The items list is loaded immediately when the order is fetched.
B. The items list is never loaded, causing a null pointer exception.
C. The items list is loaded during application startup.
D. The items list is loaded only when getItems() is called.

Solution

  1. Step 1: Understand LAZY fetch behavior on collections

    With LAZY fetch, related collections like items are not loaded immediately.
  2. Step 2: When is data loaded?

    The data loads only when the getter getItems() is called, triggering the fetch.
  3. Final Answer:

    The items list is loaded only when getItems() is called. -> Option D
  4. Quick Check:

    LAZY fetch loads on access [OK]
Hint: LAZY loads collections only on getter call [OK]
Common Mistakes:
  • Assuming collections load immediately with LAZY
  • Expecting null instead of a proxy collection
  • Confusing LAZY with EAGER behavior
4. You have a @OneToMany(fetch = FetchType.LAZY) relationship, but you get a LazyInitializationException when accessing the collection outside a transaction. What is the likely cause?
medium
A. The fetch type should be LAZY, so this exception is unexpected.
B. The collection was accessed after the session was closed.
C. The entity was not annotated with @Entity.
D. The database connection is lost.

Solution

  1. Step 1: Understand LazyInitializationException cause

    This exception happens when a LAZY collection is accessed outside an open session or transaction.
  2. Step 2: Identify session state during access

    If the session is closed before accessing the collection, the proxy cannot load data, causing the exception.
  3. Final Answer:

    The collection was accessed after the session was closed. -> Option B
  4. Quick Check:

    LazyInitializationException = access after session close [OK]
Hint: Access LAZY data only inside open session/transaction [OK]
Common Mistakes:
  • Thinking fetch type alone prevents exceptions
  • Ignoring session lifecycle in JPA
  • Blaming database connection instead
5. You have an entity Author with a @OneToMany(fetch = FetchType.LAZY) relationship to Book. You want to display all authors with their books immediately to avoid multiple queries later. Which approach is best?
hard
A. Keep LAZY fetch and use a JPQL query with JOIN FETCH to load books eagerly.
B. Use native SQL queries only to load all data at once.
C. Load authors and books separately in two queries and merge in Java code.
D. Change the fetch type to EAGER on the relationship.

Solution

  1. Step 1: Understand pros and cons of fetch types

    Changing to EAGER can cause performance issues if not always needed.
  2. Step 2: Use JOIN FETCH for selective eager loading

    JPQL with JOIN FETCH loads related entities eagerly only when needed, avoiding multiple queries.
  3. Step 3: Evaluate other options

    Loading separately or using native queries is less efficient or more complex.
  4. Final Answer:

    Keep LAZY fetch and use a JPQL query with JOIN FETCH to load books eagerly. -> Option A
  5. Quick Check:

    JOIN FETCH = selective eager loading [OK]
Hint: Use JOIN FETCH query to eagerly load LAZY relations [OK]
Common Mistakes:
  • Switching to EAGER globally causing overhead
  • Ignoring JPQL JOIN FETCH option
  • Overcomplicating with native queries