title: Getting "org.hibernate.LazyInitializationException" exceptions after retrieving items from my second-level ehcache
body: <p>I'm using Hibernate 5.1.0.Final with ehcache and Spring 3.2.11.RELEASE.  I have the following <code>@Cacheable</code> annotation set up in one of my <code>DAO</code>s:</p>
  
  <pre><code>@Override
  @Cacheable(value = "main")
  public Item findItemById(String id)
  {
      return entityManager.find(Item.class, id);
  }
  </code></pre>
  
  <p>The item being returned has a number of assocations, some of which are lazy.  So for instance, it (eventually) references the field:</p>
  
  <pre><code>@ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "product_category", joinColumns = { @JoinColumn(name = "PRODUCT_ID") }, inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID") })
  private List&lt;Category&gt; categories;
  </code></pre>
  
  <p>I notice that within one of my methods that I mark as <code>@Transactional</code>, when the above method is retrieved from the second level cache, I get the below exception when trying to iterate over the categories field:</p>
  
  <pre><code>@Transactional(readOnly=true)
  public UserContentDto getContent(String itemId, String pageNumber) throws IOException
  {
      Item Item = contentDao.findItemById(ItemId);
     …
     // Below line causes a “LazyInitializationException” exception
     for (Category category : item.getParent().getProduct().getCategories())
      {
  </code></pre>
  
  <p>The stack trace is:</p>
  
  <pre><code>16:29:42,557 INFO  [org.directwebremoting.log.accessLog] (ajp-/127.0.0.1:8009-18) Method execution failed: : org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.mainco.subco.ecom.domain.Product.standardCategories, could not initialize proxy - no Session
      at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:579) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
      at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:203) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
      at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:558) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
      at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:131) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
      at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277) [hibernate-myproject-5.1.0.Final.jar:5.1.0.Final]
      at org.mainco.subco.ebook.service.ContentServiceImpl.getCorrelationsByItem(ContentServiceImpl.java:957) [myproject-90.0.0-SNAPSHOT.jar:]
      at org.mainco.subco.ebook.service.ContentServiceImpl.getContent(ContentServiceImpl.java:501) [myproject-90.0.0-SNAPSHOT.jar:]
      at sun.reflect.GeneratedMethodAccessor819.invoke(Unknown Source) [:1.6.0_65]
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_65]
      at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_65]
      at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) [spring-tx-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) [spring-aop-3.2.11.RELEASE.jar:3.2.11.RELEASE]
      at com.sun.proxy.$Proxy126.getContent(Unknown Source)
  </code></pre>
  
  <p>I understand what the Hibernate session is closed — I do not care about why this happens.  Also, it is NOT an option o make the above association eager (instead of lazy).  Given that, how can I solve this problem?  </p>
  
  <p><b>Edit:</b> Here is how my ehccahe.xml is configured …</p>
  
  <pre><code>&lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd" updateCheck="false"&gt;
      &lt;!-- This is a default configuration for 256Mb of cached data using the JVM's heap, but it must be adjusted
           according to specific requirement and heap sizes --&gt;
      &lt;defaultCache maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="86400"
           timeToLiveSeconds="86400"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"&gt;
      &lt;/defaultCache&gt; 
      &lt;cache name="main" maxElementsInMemory="10000" /&gt;   
       &lt;cacheManagerPeerProviderFactory
           class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
           properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
           multicastGroupPort=4446, timeToLive=32"/&gt;
      &lt;cacheManagerPeerListenerFactory
          class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
          properties="hostName=localhost, port=40001,
          socketTimeoutMillis=2000"/&gt;    
  &lt;/ehcache&gt;
  </code></pre>
  
  <p>and here is how I’m plugging it into my Spring context …</p>
  
  <pre><code>&lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
      &lt;property name="packagesToScan" value="org.mainco.subco" /&gt;
      &lt;property name="jpaVendorAdapter"&gt;
          &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/&gt;
      &lt;/property&gt;
      &lt;property name="dataSource" ref="dataSource"/&gt;
      &lt;property name="jpaPropertyMap" ref="jpaPropertyMap" /&gt;
  &lt;/bean&gt;
  
  &lt;cache:annotation-driven key-generator="cacheKeyGenerator" /&gt;
  
  &lt;bean id="cacheKeyGenerator" class="org.mainco.subco.myproject.util.CacheKeyGenerator" /&gt;
  
  &lt;bean id="cacheManager"
          class="org.springframework.cache.ehcache.EhCacheCacheManager"
          p:cacheManager-ref="ehcache"/&gt;
  
  &lt;bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:configLocation="classpath:ehcache.xml"
          p:shared="true" /&gt;
  
  &lt;util:map id="jpaPropertyMap"&gt;
      &lt;entry key="hibernate.show_sql" value="false" /&gt;
      &lt;entry key="hibernate.hbm2ddl.auto" value="validate"/&gt;
          &lt;entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/&gt;
          &lt;entry key="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" /&gt;
          &lt;entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/&gt;
          &lt;entry key="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/&gt;
          &lt;entry key="hibernate.cache.use_second_level_cache" value="true" /&gt;
          &lt;entry key="hibernate.cache.use_query_cache" value="false" /&gt;
          &lt;entry key="hibernate.generate_statistics" value="false" /&gt;
  &lt;/util:map&gt;
  
  &lt;bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean"&gt;
      &lt;property name="entityManagerFactory" ref="entityManagerFactory"/&gt;
  &lt;/bean&gt;
  </code></pre>