Spring MVC load many to many relations
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 collectio开发者_开发技巧n of role: beans.Restaurant.tags, no session or session was closed
You need to use an open session in view pattern. Add the first thing in your web.xml
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
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.
精彩评论