Hibernate 例外「ロールのコレクションを遅延初期化できませんでした」を解決する方法 質問する

Hibernate 例外「ロールのコレクションを遅延初期化できませんでした」を解決する方法 質問する

これは例外です:

org.hibernate.LazyInitializationException: ロールのコレクションを遅延初期化できませんでした: mvc3.model.Topic.comments、セッションがないか、セッションが閉じられました

モデルは次のとおりです。

@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<Comment> comments = new LinkedHashSet<Comment>();

    ...

    public Collection<Comment> getComments() {
           return comments;
    }

}

モデルを呼び出すコントローラーは次のようになります。

@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<Comment> commentList = topicById.getComments();
    
        Hashtable modelData = new Hashtable();
        modelData.put("topic", topicById);
        modelData.put("commentList", commentList);
    
        return new ModelAndView("/topic/details", modelData);       
     }
}

jsp ページは次のようになります。

<%@page import="com.epam.mvc3.helpers.Utils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
    <head>
        <title>View Topic</title>
    </head>
    <body>
        <ul>
            <c:forEach items="${commentList}" var="item">
                <jsp:useBean id="item" type="mvc3.model.Comment"/>
                <li>${item.getText()}</li>
            </c:forEach>
        </ul>
    </body>
</html>

jspを表示すると例外が発生します。c :forEachループの行で

ベストアンサー1

Commentを取得するたびにすべての を表示する場合はTopic、 のフィールド マッピングを次のように変更しますcomments

@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();

コレクションはデフォルトで遅延ロードされます。これもっと詳しく知りたい場合。

おすすめ記事