Is there a helper to know whether a property has been loaded by Hibernate?
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.g开发者_高级运维etChildList());
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.
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");
精彩评论