I am a newbie to Java Persistence API and Hibernate.
What is the difference between FetchType.LAZY
and FetchType.EAGER
in Java Persistence API?
I am a newbie to Java Persistence API and Hibernate.
What is the difference between FetchType.LAZY
and FetchType.EAGER
in Java Persistence API?
From the Javadoc:
E.g., eager is more proactive than lazy. Lazy only happens on first use (if the provider takes the hint), whereas with eager things (may) get pre-fetched.
The
Lazy
Fetch type is by default selected by Hibernate unless you explicitly markEager
Fetch type. To be more accurate and concise, difference can be stated as below.FetchType.LAZY
= This does not load the relationships unless you invoke it via the getter method.FetchType.EAGER
= This loads all the relationships.Pros and Cons of these two fetch types.
Lazy initialization
improves performance by avoiding unnecessary computation and reduce memory requirements.Eager initialization
takes more memory consumption and processing speed is slow.Having said that, depends on the situation either one of these initialization can be used.
I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after
session.close()
statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.@drop-shadow if you're using Hibernate, you can call
Hibernate.initialize()
when you invoke thegetStudents()
method: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.EAGER
loading of collections means that they are fetched fully at the time their parent is fetched. So if you haveCourse
and it hasList<Student>
, all the students are fetched from the database at the time theCourse
is fetched.LAZY
on the other hand means that the contents of theList
are fetched only when you try to access them. For example, by callingcourse.getStudents().iterator()
. Calling any access method on theList
will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around theList
(orSet
). So for your lazy collections, the concrete types are notArrayList
andHashSet
, butPersistentSet
andPersistentList
(orPersistentBag
)