Java.Hibernate.Beginner.What is lazy loading in Hibernate?

Lazy loading in Hibernate means delaying the retrieval of an associated entity or collection from the database until it’s actually accessed in your code.
It helps avoid unnecessary database queries and improves performance by loading only what you need, when you need it.


🔹 How does it work?

  • When you fetch an entity with lazy-loaded associations, Hibernate initially loads only the entity itself.
  • The associated entities or collections are represented as proxies — lightweight placeholders.
  • The first time you access a lazy association, Hibernate triggers an SQL query to load the actual data.

🔹 Why use lazy loading?
Performance → avoids loading large graphs of related entities you might never use.
Efficiency → reduces initial SQL queries, memory usage, and network traffic.


🔹 How to enable lazy loading:
Hibernate uses lazy loading by default for most associations:

  • @OneToMany and @ManyToMany → lazy by default.
  • @ManyToOne and @OneToOne → eager by default (but can be changed).

You explicitly control fetch strategy with the fetch attribute:

@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;

🔹 Example:

Session session = sessionFactory.openSession();

User user = session.get(User.class, 1L); // loads User only

// At this point, user.getOrders() is not yet loaded from DB!

List<Order> orders = user.getOrders();  // triggers SQL SELECT when accessed

session.close();

🔹 What happens behind the scenes?

  • Hibernate creates a proxy for user.getOrders().
  • When you call user.getOrders() for the first time, Hibernate issues an SQL query like:
SELECT * FROM orders WHERE user_id = ?

🔹 Important caution: LazyInitializationException
✅ If you access a lazy-loaded association after the session is closed, you’ll get LazyInitializationException, because Hibernate can’t fetch data outside an active session.

Example problematic case:

User user = session.get(User.class, 1L);
session.close();
List<Order> orders = user.getOrders(); // 💥 throws LazyInitializationException

Key takeaway:
Lazy loading in Hibernate defers loading of associations until they’re accessed, boosting performance by avoiding unnecessary data loading — but requires careful session management to avoid LazyInitializationException.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.