I got relations many to many between restaurant and tag. Here are my classes:
public class Restaurant {
@Id
@GeneratedValue
private int id;
(...)
@ManyToMany
@JoinTable(name="restaurant_tag",
joinColumns={@JoinColumn(name="restaurant_id")},
inverseJoinColumns={@JoinColumn(name="tag_id")})
private List<Tag> tags;
and:
public class Tag {
@Id
private int id;
private String name;
@ManyToMany
@JoinTable(name="restaurant_tag",
joinColumns={@JoinColumn(name="tag_id")},
inverseJoinColumns={@JoinColumn(name="restaurant_id")})
private List<Restaurant> restaurants;
I want to displays all the tags connected with my restaurant. Here’s controller:
modelMap.addAttribute("tagList", restaurant.getTags());
In my jsp:
<c:forEach items="${tagList }" var="var"><c:out value="${var }" ></c:out></c:forEach>
When i go to the restaurant page, i got error:
org.hibernate.LazyInitializationException:
failed to lazily initialize a
collection of role:
beans.Restaurant.tags, no session or
session was closed
This happens because your DAO closes the hibernate session before the collection can be fetched.
Have a look at the “Open Session In View” pattern, this is the most common solution to this problem.