Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.getChildList());
like image 557
Arthur Ronald Avatar asked Oct 19 '09 14:10

Arthur Ronald


People also ask

How to handle Hibernate exceptions?

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.

When exception happens in Hibernate?

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.

How do you initialize a lazy load?

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.

What happens when the no args constructor is absent in the entity bean?

So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get `HibernateException`.


2 Answers

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");
like image 68
vzhemevko Avatar answered Sep 26 '22 01:09

vzhemevko


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.

like image 32
ChssPly76 Avatar answered Sep 24 '22 01:09

ChssPly76