I am attempting to create a web application using Spring MVC, with Hibernate as its ORM layer. However, due to my inexperience with both frameworks I\'m struggling.
I just went through this LazyInitialization marathon.
The core problem is that you're trying to access an hibernate-managed entity outside of the lifecycle of the Session
, i.e. in the web view of Spring MVC. In my case, this was a List<>
@OneToMany
association, which are lazily loaded by default.
There are a few different approaches -- Mark mentioned one, where you do a "dummy" iteration over the lazy associations. You can also force eager loading, either via the configuration (class-wide) (in JPA it'd be @Fetch(value = FetchType.EAGER)
) or more specifically through the HQL. But this will prove more problematic if your lazy associations are Lists.
The cleanest solution I found was to use Spring's OpenEntityManagerInViewFilter (there's an OpenSessionInViewFilter
for Hibernate) -- a simple servlet filter you drop in to web.xml
(ahead of your other servlet filters), and Spring will automatically create a thread-safe, transaction-aware Session
per-HTTP-request. No more LazyInitializationException
!