How to set the id on detached Hibernate proxy without LazyInitializationException?

719 Views Asked by At

I'm using the object, which has over 15 related entities (parents). In my UI side I need only the ids of these entities, so I don't need Hibernate's fetch functionality and I use the lazy proxy concept to avoid the hit to database on the one hand and to have the objects with populated ids on the other.

To achieve this I have to use property acces instead of field access for all parent entities:

@Id
@Access(AccessType.PROPERTY) // this helps to avoid database hit on get, but not on set!!!    
private Long id;

So far so good, I load the object from database (no extra joins are made) and show it on the web UI with all relations (simple select inputs at most). I don't create clones (value objects) for UI, I use the detached hibernate objects directly. But when I do any changes to UI (change the parent object) the framework calls setId() for related proxy entities and .... this results in initialization of these proxies! Here is the code from Hibernate BasicLazyInitializer which does this:

else if ( method.equals(setIdentifierMethod) ) {
        initialize(); // Here the db hit occurs!!
        setIdentifier( (Serializable) args[0] );
        return INVOKE_IMPLEMENTATION;
     }

and the LazyInitializationException occurs (sure, I have no session at this point of time!).

So, is there any approach to do this without creation of value objects for all entities, fetched from database? I can say, that I always used data objects in UI directly, but they all were fetched completely (not proxies) and I haven't had such problems as now with these proxies...

I really don't understand, why Hibernate makes the proxy initialization on setting (though doesn't do on getting) the @ID field...

Thanks in advance!

0

There are 0 best solutions below