12

I need a helper to know whether a property has been loaded as a way to avoid LazyInitializationException. Is it possible?

@Entity
public class Parent {
    @OneToMany
    private List<Child> childList;
}

@Entity
public class Child {

}

"select distinct p from Parent p left join fetch p.childList";

// Answer goes here
// I want to avoid LazyInitializationException
SomeHelper.isLoaded(p.getChildList());
Svante
  • 50,694
  • 11
  • 78
  • 122
Arthur Ronald
  • 33,349
  • 20
  • 110
  • 136

2 Answers2

16

There are two methods, actually.

To find out whether a lazy property has been initialized you can invoke Hibernate.isPropertyInitialized() method with your entity instance and property name as parameters.

To find out whether a lazy collection (or entity) has been initialized (like in your example) you can invoke Hibernate.isInitialized() with collection (entity) instance as parameter.

ChssPly76
  • 99,456
  • 24
  • 206
  • 195
4

According to the documentation for Hibernate 5.4

Hibernate API

boolean personInitialized = Hibernate.isInitialized(person);

boolean personBooksInitialized = Hibernate.isInitialized(person.getBooks());

boolean personNameInitialized = Hibernate.isPropertyInitialized(person, "name");

JPA

In JPA there is an alternative means to check laziness using the following javax.persistence.PersistenceUtil pattern (which is recommended wherever possible).

PersistenceUtil persistenceUnitUtil = Persistence.getPersistenceUtil();

boolean personInitialized = persistenceUnitUtil.isLoaded(person);

boolean personBooksInitialized = persistenceUnitUtil.isLoaded(person.getBooks());

boolean personNameInitialized = persistenceUnitUtil.isLoaded(person, "name");
vzhemevko
  • 815
  • 8
  • 25
  • Interesting enough, `hibernate.isPropertyInitialized` didn't do the job. Only `persistenceUnitUtil.isLoaded` worked for me. As I am uing JPA over hibernate. – A. Parolini Sep 10 '21 at 14:46