tags:

views:

69

answers:

1
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.

+1  A: 

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.

Thierry-Dimitri Roy
that's a very interesting solution, it obviously has a downside that the entity becomes tightly coupled to hibernate, but unless there is an answer that does it without the coupling I think this is the winner
walnutmon