gpt4 book ai didi

java - 如何解决Hibernate异常 “failed to lazily initialize a collection of role”

转载 作者:行者123 更新时间:2023-12-02 01:50:37 25 4
gpt4 key购买 nike

我有这个问题:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: mvc3.model.Topic.comments, no session or session was closed

这是模型:

@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 如下所示:

@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 循环的行

最佳答案

如果您知道每次检索主题时都希望看到所有评论,请更改评论的字段映射至:

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

集合默认是延迟加载的,看看this如果您想了解更多。

关于java - 如何解决Hibernate异常 “failed to lazily initialize a collection of role”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com