A while ago at Baa Camp I was talking to a few of the Java attendees about various pain points I've had with Hibernate/JPA lazy loading - from loading data in JSP to iterating a collection in a controller class thats not at the DAO layer to access a collection/linked object after the objects been sent over RMI to a remote host.
I've tried numerous times to the OpenSessionInView pattern but for some reason it just never seems to work for me - maybe there's something non-obvious I'm doing in my code base but I can't see it.
Anyway, I was trying to find out if anyone had looked at solving the problem by storing a JNDI reference to the appropriate SessionFactory/EntityManager and using that when required. When its in my head it seems as thou theres little problems with the idea: when generating your dynamic proxies you'd include a string copy of a JNDI reference and a transient SessionFactory, when accessing a lazy property thats not loaded, lookup the SessionFactory if needed and do your thing.
The only thing's that comes to mind would be the cost of binding and looking up JNDI all the time, thou I'm sure you could do some magic caching of the SessionFactory instance.
Surely someone must have looked at this and found some reasons not to use it? Anyone know?
If you do that without solving your open session in view problem, I think
you will have objects loaded in multiple persistence contexts and no end to
the object identity issues that could ensue. You are much better backing
up and figuring out why open session in view isn't working. Another option
would be to take a look at how Seam handles this. Seam solves the
Hibernate lazy instantiation problem by using Hibernate the way it was
meant to be used.