Component Inspector
Click on components to learn about fetch strategies, or run a simulation to see how data is loaded.
Simulation Legend
Memory State (L1 Cache)
u.getProfile(); // Triggers load
JPA Fetch Types: Eager vs. Lazy Loading
When dealing with relational data in ORMs like Hibernate, you rarely load just one entity. Entities are connected (e.g., a `User` has a `Profile`, an `Order` has `Items`). Fetch Strategies dictate when these associated entities are loaded from the database into application memory.
FetchType.EAGER
"Give it to me NOW"
When you load the parent entity, Hibernate immediately issues SQL queries (often
using a JOIN) to fetch all EAGERly mapped child associations. The parent and
children arrive in memory together.
Default for: @ManyToOne, @OneToOne
@Entity
public class User {
@Id private Long id;
// Loaded immediately when User is loaded
@OneToOne(fetch = FetchType.EAGER)
private UserProfile profile;
}
Danger: Overusing EAGER fetching leads to the "Cartesian Product" problem, loading massive amounts of unnecessary data and slowing down your application.
FetchType.LAZY
"I'll get it when I need it"
When you load the parent entity, Hibernate fetches only the parent data.
For the child associations, it injects a Proxy Object. A proxy is an empty
shell that looks like the real object but contains no data. The real data is only fetched via a
new SQL query when you actually call a method on the proxy (like profile.getBio()).
Default for: @OneToMany, @ManyToMany
@Entity
public class User {
@Id private Long id;
// A Proxy is injected. Data loaded only when accessed.
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<Order> orders;
}
Best Practice: Always prefer LAZY loading to conserve memory and network bandwidth.
If you need eager behavior for a specific query, use a JOIN FETCH in JPQL.
The LazyInitializationException
The most famous JPA error. If you attempt to access a LAZY loaded association (triggering the proxy to fetch data) after the database transaction has closed, Hibernate cannot execute the query, resulting in this exception.