title: How to solve the “failed to lazily initialize a collection of role” Hibernate exception
body: <p>I have this problem:</p>
  
  <blockquote>
    <p>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mvc3.model.Topic.comments, no session or session was closed</p>
  </blockquote>
  
  <p>Here is the model:  </p>
  
  <pre><code>@Entity
  @Table(name = "T_TOPIC")
  public class Topic {
  
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private int id;
  
      @ManyToOne
      @JoinColumn(name="USER_ID")
      private User author;
  
      @Enumerated(EnumType.STRING)    
      private Tag topicTag;
  
      private String name;
      private String text;
  
      @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL)
      private Collection&lt;Comment&gt; comments = new LinkedHashSet&lt;Comment&gt;();
  
      ...
  
      public Collection&lt;Comment&gt; getComments() {
             return comments;
      }
  
  }
  </code></pre>
  
  <p>The controller, which calls model looks like the following:</p>
  
  <pre><code>@Controller
  @RequestMapping(value = "/topic")
  public class TopicController {
  
      @Autowired
      private TopicService service;
  
      private static final Logger logger = LoggerFactory.getLogger(TopicController.class);
  
  
      @RequestMapping(value = "/details/{topicId}", method = RequestMethod.GET)
      public ModelAndView details(@PathVariable(value="topicId") int id)
      {
  
              Topic topicById = service.findTopicByID(id);
              Collection&lt;Comment&gt; commentList = topicById.getComments();
  
              Hashtable modelData = new Hashtable();
              modelData.put("topic", topicById);
              modelData.put("commentList", commentList);
  
              return new ModelAndView("/topic/details", modelData);
  
       }
  
  }
  </code></pre>
  
  <p>The jsp-page looks li the following:</p>
  
  <pre><code>&lt;%@page import="com.epam.mvc3.helpers.Utils"%&gt;
  &lt;%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%&gt;
  &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt;
  &lt;%@ page session="false" %&gt;
  &lt;html&gt;
  &lt;head&gt;
        &lt;title&gt;View Topic&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;ul&gt;
  &lt;c:forEach items="${commentList}" var="item"&gt;
  &lt;jsp:useBean id="item" type="mvc3.model.Comment"/&gt;
  &lt;li&gt;${item.getText()}&lt;/li&gt;
  
  &lt;/c:forEach&gt;
  &lt;/ul&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Exception is rised, when viewing jsp. In the line with <em>c:forEach</em> loop</p>