Issue
In a Spring Boot project I am working at I added the Hibernate ORM plugin to enable lazy loading for @Lob
fields in my entity, this didn't work out of the box for DB2. The lazy loading works, when I retrieve the object the lob field isn't loaded yet. But now a new problem occurs, when I do want to get the blob field I get a LazyInitializationException
. Now I did some debugging and Google searches. I tried to add @Transactional
to the method and to the classes, I also tried multiple propagation options, but nothing works.
I also tried to load the object directly using the EntityManager, but that also gives the same exception:
Object object = entityManager.find(Object.class, id);
object.getLobField();
The full exception that is thrown is:
org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [package.Object.lobField] - no session and settings disallow loading outside the Session
Solution
You need to activate in your application.yml
spring:
jpa:
properties:
hibernate:
enable_lazy_load_no_trans: true
This will allow lazy loading to work outside the session that created the object that has properties that are lazy loaded.
Reference: https://www.baeldung.com/hibernate-lazy-loading-workaround, Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans and https://vladmihalcea.com/the-hibernate-enable_lazy_load_no_trans-anti-pattern/
Answered By - pringi
Answer Checked By - David Goodson (JavaFixing Volunteer)