Why am I getting a Hibernate LazyInitializationException in this Spring MVC web application when the data displays correctly?

后端 未结 6 403
太阳男子
太阳男子 2020-12-29 11:31

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.

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 11:48

    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!

提交回复
热议问题