JPA: which implementations support lazy loading outside transactions?

Alexey Romanov picture Alexey Romanov · Apr 15, 2012 · Viewed 8k times · Source

EclipseLink can load lazy relationships in entities even after the entity manager that has created them is no longer available. With Hibernate this doesn't work, or at least didn't at the time of that post.

What about other providers? OpenJPA and DataNucleus in particular?

What are the downsides to this (except more complex implementation)?

Answer

Tim Pote picture Tim Pote · Apr 16, 2012

Although Hibernate does require the same EntityManager to be available in order to lazily load objects, it is easy to achieve flexible lazy loading with the Open Session in View Pattern. In essence, you keep the EntityManager open as long as you need it. I've developed client-side applications that keep the same EntityManager open as long as the application is open. This would give you essentially the same behavior described in the article. However, it is certainly more difficult to implement than the "out of the box" lazy loading Roman describes.

All that being said, there are downsides to lazy loading. The developer has to be aware of his fetching strategy and must be capable of differentiating when and where each strategy is most applicable. Otherwise you can end up with serious performance issues like the N+1 Select Problem. Plus there's always the possibility that you'll get a database exception during the rendering of the view.

About OpenJPA and DataNucleus: Although I've never used either, this post indicates that OpenJPA also requires an OpenSessionInViewFilter for lazy loading. This SO answer and this forum post indicate that DataNucleus requires an OpenPersistenceManagerInViewFilter for lazy loading.