I tend to use Hibernate in combination with Spring framework and it's declarative transaction demarcation capabilities (e.g., @Transactional).
As we all known, hibernate tries to be as non-invasive and as transparent as possible, however this proves a bit more challenging when employing lazy-loaded
relationships.
I see a number of design alternatives with different levels of transparency.
fetchType=FetchType.EAGER)
Hibernate.initialize(proxyObj);
initialize
, other implementations are not guaranteed to provide any equivalent. Model
objects themselves (using either dynamic proxy or @Transactional
)
loadData()
and loadDataWithDeps()
loadDataWithA()
, ...., loadDataWithX()
byId()
operations
findZzzById(zid)
, and then getYyyIds(zid)
instead of z.getY()
loadData(id, fetchProfile);
Did I miss any option?
Which is your preferred approach when trying to minimize the impact of lazy-loaded
relationships in your application design?
(Oh, and sorry for WoT)
As we all known, hibernate tries to be as non-invasive and as transparent as possible
I would say the initial assumption is wrong. Transaparent persistence is a myth, since application always should take care of entity lifecycle and of size of object graph being loaded.
Note that Hibernate can't read thoughts, therefore if you know that you need a particular set of dependencies for a particular operation, you need to express your intentions to Hibernate somehow.
From this point of view, solutions that express these intentions explicitly (namely, 2, 4 and 7) look reasonable and don't suffer from the lack of transparency.