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());
Hibernate provides better handle than the JDBCException . Developers can use the try and catch block to handle the exceptions. Put the line of code that may cause an exception in a try block and according to that exception put the exception handler in the catch block.
Many conditions can cause exceptions to be thrown while using Hibernate. These can be mapping errors, infrastructure problems, SQL errors, data integrity violations, session problems, and transaction errors. These exceptions mostly extend from HibernateException.
So, if we want to configure lazy initialization for a specific bean, we can do it through the @Lazy approach. Even more, we can use the new property, in combination with the @Lazy annotation, set to false.
So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get `HibernateException`.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With