Fetch types decide when related data is loaded from the database. They help control performance and memory use.
Fetch types (LAZY vs EAGER) in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
@OneToMany(fetch = FetchType.LAZY) private List<Item> items; @OneToMany(fetch = FetchType.EAGER) private List<Item> items;
Use fetch = FetchType.LAZY to load data only when accessed.
Use fetch = FetchType.EAGER to load data immediately with the main entity.
getOrders().@OneToMany(fetch = FetchType.LAZY) private List<Order> orders;
@ManyToOne(fetch = FetchType.EAGER) private Customer customer;
@OneToOne(fetch = FetchType.LAZY) private Profile profile;
This example shows a User with many Posts. Posts load only when accessed (LAZY). Each Post loads its User immediately (EAGER). This balances performance and convenience.
import jakarta.persistence.*; import java.util.List; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") private List<Post> posts; public User() {} public User(String name) { this.name = name; } public List<Post> getPosts() { return posts; } public String getName() { return name; } } @Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; @ManyToOne(fetch = FetchType.EAGER) private User user; public Post() {} public Post(String content, User user) { this.content = content; this.user = user; } public String getContent() { return content; } public User getUser() { return user; } } // Explanation: // When loading a User, posts are not loaded immediately (LAZY). // When loading a Post, the User is loaded immediately (EAGER). // This helps avoid loading all posts unless needed, but always loads the user with a post.
LAZY loading can cause errors if accessed outside a database session.
EAGER loading can slow down queries if many related objects exist.
Choose fetch type based on how and when you need related data.
Fetch types control when related data loads: LAZY delays loading, EAGER loads immediately.
Use LAZY to save resources and EAGER for quick access to related data.
Pick the right fetch type to balance performance and convenience in your app.
Practice
LAZY fetch type do in Spring Boot JPA?Solution
Step 1: Understand fetch types in JPA
Fetch types control when related data is loaded from the database.Step 2: Define LAZY fetch behavior
LAZY means related entities are loaded only when you access them, not immediately.Final Answer:
It delays loading related entities until they are accessed. -> Option CQuick Check:
LAZY = delayed loading [OK]
- Confusing LAZY with EAGER loading
- Thinking LAZY loads data immediately
- Assuming LAZY disables loading
Solution
Step 1: Identify correct annotation and fetch type
EAGER fetch type is set usingfetch = FetchType.EAGERinside relationship annotations.Step 2: Match correct relationship and fetch type
@ManyToOne(fetch = FetchType.EAGER) uses@ManyToOne(fetch = FetchType.EAGER), which is valid and correct.Final Answer:
@ManyToOne(fetch = FetchType.EAGER) -> Option AQuick Check:
EAGER fetch uses FetchType.EAGER [OK]
- Using LAZY instead of EAGER for eager loading
- Mixing relationship types with wrong fetch types
- Forgetting to specify fetch attribute
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
Solution
Step 1: Understand LAZY fetch behavior on collections
With LAZY fetch, related collections likeitemsare not loaded immediately.Step 2: When is data loaded?
The data loads only when the gettergetItems()is called, triggering the fetch.Final Answer:
The items list is loaded only when getItems() is called. -> Option DQuick Check:
LAZY fetch loads on access [OK]
- Assuming collections load immediately with LAZY
- Expecting null instead of a proxy collection
- Confusing LAZY with EAGER behavior
@OneToMany(fetch = FetchType.LAZY) relationship, but you get a LazyInitializationException when accessing the collection outside a transaction. What is the likely cause?Solution
Step 1: Understand LazyInitializationException cause
This exception happens when a LAZY collection is accessed outside an open session or transaction.Step 2: Identify session state during access
If the session is closed before accessing the collection, the proxy cannot load data, causing the exception.Final Answer:
The collection was accessed after the session was closed. -> Option BQuick Check:
LazyInitializationException = access after session close [OK]
- Thinking fetch type alone prevents exceptions
- Ignoring session lifecycle in JPA
- Blaming database connection instead
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?Solution
Step 1: Understand pros and cons of fetch types
Changing to EAGER can cause performance issues if not always needed.Step 2: Use JOIN FETCH for selective eager loading
JPQL with JOIN FETCH loads related entities eagerly only when needed, avoiding multiple queries.Step 3: Evaluate other options
Loading separately or using native queries is less efficient or more complex.Final Answer:
Keep LAZY fetch and use a JPQL query with JOIN FETCH to load books eagerly. -> Option AQuick Check:
JOIN FETCH = selective eager loading [OK]
- Switching to EAGER globally causing overhead
- Ignoring JPQL JOIN FETCH option
- Overcomplicating with native queries
