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"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
      <list>
        <ref bean="openSessionInViewInterceptor" />
     </list>
    </property>
   <!-- ... -->
</bean>

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

<bean name="openSessionInViewInterceptor"
  class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
      <ref bean="sessionFactory" />
    </property>
</bean>

Dynamic Menus with SiteMesh

Today I created a dynamic menu which highlights the menu tab that corresponds to the page that is being shown. I am using SiteMesh and the main menu of my web pages is created in the main decorator so that it appears in every page. The problem was in knowing which page was being decorated. After searching in Google I found two entries at Tongue and Groove and Raible Designs that helped me figure out the solution.

In the JSP page add a the following code:

<head>
  <meta name="menu" content="home" />
</head>

Then, in the decorator, you can get that property by doing:

<c:set var="selectedMenu" scope="request">

  <decorator:getProperty property='meta.menu' />

</c:set>

Now the only thing left is to create the actual menu like this:

<c:url var="homepath" value="/" />
<div id="menu">

  <ul>

    <li><a class="${selectedMenu == 'home' ? 'selected' : ''}"

      href="${homepath}">Home</a></li>

    <li><%--more menu tabs here--%></li>

  </ul>

</div>

And don’t forget to style the class selected in the css file (for example):

#menu a.selected {

  color: #428ce7;

}