To fetch lazy object, you need to invoke Hibernate.initialize(proxy) e.g. in your service class:
public <R> R fetchLazy(T entity, Function<T,R> proxyMapper) {
entity = ensureEntityHasOpenedSession(entity);
R proxy = proxyMapper.apply(entity);
Hibernate.initialize(proxy);
return proxy;
}
Outside of the service scope one would need to call:
AnotherEntity another = service.fetchLazy(entity, Entity::getAnotherEntity);
Now, the question is why this works:
another.getId();
while subsequent call does not:
entity.getAnotherEntity().getId(); // LazyInitializationException
Has not been AnotherEntity stored in Entity after first fetch? Do I always need to call
service.fetchLazy(entity, Entity::getAnotherEntity).getSomething();
If so, does Hibernate.initialize(Object) return cached proxy at second call or there is always another database access (query execution)?
EDIT
I'm using JPA annotations on private class fields in combination with lombok's @Getter @Setter annotations.