How to fix LazyInitializationException

I wanted to show the number of items in a certain category and what I get is a LazyInitializationException (failed to lazily initialize a collection of role – no session or session was closed). It seems that because the fetch mode for the collection items is lazy, the session is not available anymore when I actually need it.

The solution is to add an interceptor to the UrlHandlerMapping in the dispatcher servlet like so:

<bean id="urlMapping"
    <property name="interceptors">
        <ref bean="openSessionInViewInterceptor" />
   <!-- ... -->

That interceptor is a OpenSessionInViewInterceptor which will make the session available in the view layer.

<bean name="openSessionInViewInterceptor"
    <property name="sessionFactory">
      <ref bean="sessionFactory" />

2 thoughts on “How to fix LazyInitializationException

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s