Issue
There is a scenario I have encountered, where I'm returning the API response(request thread) and delegating the task to a background thread.
In the background thread, I'm calling hibernate's T getOne(ID id);
to fetch some information, which is resulting in
org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Thread class
But, when performing DB operations with JPA queries @Query("some query")
, native query @Query(value = "some query", native = true)
and JdbcTemplate, it's working fine in the background thread.
Can someone help me understand why such behaviour?
FYI.. I'm using Spring Boot 1.4.2 and Hibernate 5.0.11
Solution
T getOne(ID id)
relies on EntityManager.getReference()
that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.
Basically your thread is unable to find any active sessions context.Hibernate
throws the LazyInitializationException
when it needs to initialize a lazily fetched association to another entity without an active session context.
You FetchType.EAGER
in any of the associations you are having w.r.t to the object you are trying to get. But, it can have its own repercussions like unwanted query execution every time you try to get object.
Best Solution will be using Optional<T> findById(ID id)
You can get check if entity exists using obj.isPresent()
and continue.
Answered By - Rachit3017
Answer Checked By - Cary Denson (JavaFixing Admin)