I am a newbie to Java Persistence API and Hibernate.
What is the difference between FetchType.LAZY and FetchType.EAGER in Java Persistence API?
LAZY: It fetches the child entities lazily i.e at the time of fetching parent entity it just fetches proxy(created by cglib or any other utility) of the child entities and when you access any property of child entity then it is actually fetched by hibernate.
EAGER: it fetches the child entities along with parent.
For better understanding go to Jboss documentation or you can use hibernate.show_sql=true
for your app and check the queries issued by the hibernate.
The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.
Eager fetch
Lazy fetch
@drop-shadow if you're using Hibernate, you can call Hibernate.initialize()
when you invoke the getStudents()
method:
Public class UniversityDaoImpl extends GenericDaoHibernate<University, Integer> implements UniversityDao {
//...
@Override
public University get(final Integer id) {
Query query = getQuery("from University u where idUniversity=:id").setParameter("id", id).setMaxResults(1).setFetchSize(1);
University university = (University) query.uniqueResult();
***Hibernate.initialize(university.getStudents());***
return university;
}
//...
}