开发者

hibernate relationship jstl question

Im following a hibernate tutorial in which my database has a relationship between "Person"s and "Events"

there is a many-to-many relationship between the two. Each Person has a set of events in the Person.class, that i can access programatically using personinstance.getEvents()

heres what i want to work:

the controller(excerpt):

List<Person> persons = personManager.getPersons();
    Map<String, Object> myModel = new HashMap<String, Object>();
    myModel.put("persons", persons);

    return new ModelAndView("WEB-INF/jsp/hello.jsp","model",myModel);

the jsp page:

<%@ include file="include.jsp"%>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Persons</h1>
<br />
<c:forEach items="${model.persons}" var="person">
    <c:out value="${person.firstname }" />
    <c:out value="${person.lastname }" />

    <c:forEach items="${person.events }" var="event">
        <c:out value="${event.title }" />
    </c:forEach>

    <br />
</c:forEach>
</html>

the error:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: domain.Person.events, no session or session was closed

I'm not sure if I'm going about this the right way (nested for each loops usin开发者_开发技巧g jstl) or if i can achieve the result im looking for through the controller or something. but i need some advice


There are several similar questions here on stackoverflow about this. As a friendly advice, try to search for the general part of the exception before opening a new question. In this case, "no session or session was closed".

The problem is that your view is trying to access "events", which was not loaded by Hibernate when it loaded the list of Person. This is called lazy loading. If you know you'll need "events" in the view, you'll have to pre-load it before dispatching to the view. This is called eager loading. For instance, in your Person model, your @ManyToMany can look like this:

@ManyToMany(fetch = FetchType.EAGER)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜