Pages Navigation Menu

Coding is much easier than you think

Hibernate Eager vs Lazy Fetch Type

Sometimes you have two entities and there’s a relationship(OneToOne, OneToMany or ManyToMany)  between them.
 
For example, you might have an entity called University and another entity called Student. The University entity might have some basic properties such as collegeId, name, address, etc. as well as a property called students:
 

public class University {
 private String collegeId;
 private String name;
 private String address;
 private List students;

 // setters and getters
}

 
Now when you load a University from the database, Hibernate loads its collegeId, name, and address fields for you. But you have two options for students: to load it together with the rest of the fields (i.e. Eagar Fetch) or to load it on-demand (i.e. Lazy Fetch) when you call the university’s getStudents() method.
 

Pros and Cons

 
When a university has many students it is not efficient to load all of its students with it when they are not needed. So in suchlike cases, you can declare that you want students to be loaded when they are actually needed. This can be simply done by invoking university’s getStudents() method . This is called lazy loading.

Eager loading is essentially the opposite of Lazy loading, Eager will by default load ALL of the relationships related to a particular object loaded by Hibernate.

So, the long story short here is:

LAZY Fetch = Doesn’t load the relationships unless explicitly “asked for” via getter
EAGER Fetch = Loads ALL relationships

To save memory, Lazy loading is generally used for one to many and many to many relationships. For one to one, generally Eager is used

Note:

if you don’t specify this fetch type then Hibernate defaults based on JPA spec.

From the JPA 2.1 spec, the defaults are like so:

  • OneToMany:LAZY
  • ManyToOne: EAGER
  • ManyToMany: LAZY
  • OneToOne: EAGER
  • Columns : EAGER

 
Another must read
 

3 Comments

  1. plz keep all interview questions hibernate.

  2. Amazing stuff….Great job…when will you upload full tutorial on Hibernate