Lazy and eager loading in Hibernate

Suryasis Paul
2 min readApr 30, 2020

In the last few posts, we had introduced JPA and Hibernate and we had explained the difference between the two. Though a comprehensive tutorial would cover all the annotations that are used with JPA, that really is too mundane a task for a blog post. Frankly, I do not remember all the annotation and their purposes, but you can always look it up. So, what we would be focussing on are concepts and philosophies that are important for an understanding of Hibernate. And today we look into lazy and eager loading strategies.
Suppose we have an entity class as shown:

Now as is evident, since this class Student has a list of subjects, the number of these subjects can be numerous. So if we were to pull out an object of type student from the database would we need to pull out all the addresses associated with that particular restaurant? Database operations are costly operations and it turns out that this might not be the best idea.
Rather we could pull out data only when it is required. For example,

In the above code, with this strategy, when we fire the getSubjectsTaken() method, it is at that moment that the list of addresses is populated. This is called Lazy loading. However, the first level items like name and id are loaded during pulling out the object itself. Lazy loading improves performance as it delays and prevents undue calls to the database unless there is a compelling reason for the same.

The opposite of lazy loading strategy is, of course, is the eager loading strategy that fetches all the data right when the object is pulled out. It also can improve performance by reducing calls on the server.

When to use what?

The basic parameter that we use to judge between each strategy is that we need to limit the number of queries to the server.

  • It is a good idea to use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
  • Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.
  • Use Lazy Loading when you are using one-to-many collections.
  • Use Lazy Loading when you are sure that you are not using related entities instantly.

--

--