Eager fetching means loading an association immediately along with the parent entity, so related entities are retrieved in the same query (if possible) or with additional immediate queries.
This is the opposite of lazy loading: instead of deferring, eager fetching ensures associated data is always available as soon as you load the parent.
🔹 How does it work?
- When you fetch an entity with eager associations, Hibernate loads the entity and its eager associations together.
- This avoids
LazyInitializationException
, because the data is loaded while the session is still open. - But it can also load a lot of unnecessary data, hurting performance for large graphs.
🔹 How to specify eager fetching:
Use the fetch
attribute on association annotations:
@OneToMany(fetch = FetchType.EAGER)
private List<Order> orders;
🔹 What happens with eager fetch:
Example entity:
@Entity
public class User {
@OneToMany(fetch = FetchType.EAGER)
private List<Order> orders;
}
And when you load a User:
User user = session.get(User.class, 1L); // loads User + Orders immediately
✅ Hibernate either runs:
- A join query to load user and orders together in one SQL, or
- A batch of additional queries immediately to load the orders.
🔹 Why use eager fetching?
✅ Ensures associated data is always available, avoiding LazyInitializationException.
✅ Useful when you always know you’ll need the associated data.
🔹 Why not always use it?
❌ Can load large object graphs unnecessarily, especially with deeply nested relationships → increases memory usage and slows performance.
❌ More prone to N+1 query problems if you don’t design queries carefully.
🔹 Comparison:
Feature | Lazy Fetching | Eager Fetching |
---|---|---|
Load timing | Loads associations when accessed | Loads associations immediately |
Performance | Faster initial load if associations unused | Slower if associations unused |
Risk | LazyInitializationException if session closed | Loads unnecessary data |
✅ Key takeaway:
Eager fetching loads associated entities up front with the parent entity, ensuring availability but risking performance issues if associations aren’t always needed.