Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - Avoiding LazyInitializationException - Detach Object From Proxy and Session

MyObject myObject = repositoryHibernateImpl.getMyObjectFromDatabase();
//transaction is finished, and no, there is not an option to reopen it
ThirdPartyUtility.doStuffWithMyObjectType( myObject );

at this point you've already defined what is lazy and eager loaded, and the third party utility will try to call all of the methods on your "myObject" instance, this is fine because you don't want to return anything for the lazily loaded properties, unfortunately it doesn't return null, it throws a LazyInitializationException.

This happens because you're actually calling the method on Hibernate's proxy of your object, and it knows that it hasn't fetched that data, and throws an exception.

Is it even possible to get the underlying object with null values so that a getter just returns null, and doesn't throw an exception? Basically detaching the object so that Hibernate is no longer aware of it at all. The accessor to the object that is lazily loaded must return null, it cannot return the actual values, we want to be able to convert the entity into a POJO without having to create an object that looks just like the entity and has to remap all the values.

like image 329
walnutmon Avatar asked Nov 06 '22 09:11

walnutmon


1 Answers

Let's say you have a field, in the getter you could:

MyField getMyField() {
    if (Hibernate.isInitialized(myField)) {
        return myField;
    }
    return null;
}

From the javadoc of org.hibernate.Hibernate:

public static boolean isInitialized(Object proxy): check if the proxy or persistent collection is initialized.

like image 106
Thierry-Dimitri Roy Avatar answered Nov 11 '22 02:11

Thierry-Dimitri Roy