我有这个问题:
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循环一致
如果您知道Comment
每次检索a时都希望看到全部,Topic
则将字段映射更改为comments
:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
默认情况下,集合是延迟加载的,如果您想了解更多信息,请查看此内容。
抱歉,但我想使用延迟加载。因此,我更改了“ PersistentList”的“ LinkedHashSet”类型。仍然发生异常
可以将其用作解决方法,但不能真正解决问题。如果我们需要懒洋洋地拿东西怎么办?
但是如果万一我们想偷懒,那么此解决方案将无法正常工作,并且在大多数情况下,我们只想懒惰。
这是在堆栈溢出时到处弹出的答案类型。简而言之,就是解决了问题和误导。对于将来的读者,请帮个忙,并了解什么是真正的懒惰和急切获取的东西,并了解其后果。
@darrengorman当我开始JPA时,我围绕OP的内容发布了一个问题。我收到了与您相同的回复。足够快的时候,当我对成千上万的行进行测试时,您猜怎么了?我认为这具有误导性,因为它提供的答案对于大多数初学者都会遇到的问题来说太简单了,如果他们不小心的话,他们很快就会将整个数据库加载到内存中(而且他们不会,因为他们不会请注意):)。