0

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
Bart Bergmans
  • 4,061
  • 3
  • 28
  • 56

2 Answers2

1

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/

pringi
  • 3,987
  • 5
  • 35
  • 45
  • Isn't this considered an anti-pattern? – Bart Bergmans Feb 11 '22 at 11:06
  • Yes it is, as the last link refers. But sometimes there is no other option. The alternative is you to fetch (load) the necessary relations. But frequently you do not know exactly what relation need to be fetched. For example, if you use an API with filters. – pringi Feb 11 '22 at 11:09
0

Hibernate has one workaround, an enable_lazy_load_no_trans property. Turning this on means that each fetch of a lazy entity will open a temporary session and run inside a separate transaction

Try adding the below property

System.setProperty("hibernate.enable_lazy_load_no_trans", "true");