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 want to add this note to what "Kyung Hwan Min" said above.
Suppose you are using Spring Rest with this simple architect:
Controller <-> Service <-> Repository
And you want to return some data to the front-end, if you are using FetchType.LAZY
, you will get an exception after you return data to the controller method since the session is closed in the Service so the JSON Mapper Object
can't get the data.
There is three common options to solve this problem, depends on the design, performance and the developer:
FetchType.EAGER
, So that the session will still alive at the controller method.FetchType.LAZY
with converter method to transfer data from Entity
to another data object DTO
and send it to controller, so there is no exception if the session closed.