.jpg)
我有这个问题:
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;
}
}
调用 model 的控制器如下所示:
@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 看起来如下所示:
<%@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 循环的行中

如果您知道每次检索 时都希望看到所有 s,请将字段映射更改为:CommentTopiccomments
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
默认情况下,集合是延迟加载的,如果您想了解更多信息,请查看此内容。

根据我的经验,我有以下方法来解决著名的 LazyInitializationException:
(1) 使用休眠初始化
Hibernate.initialize(topics.getComments());
(2) 使用加入获取
您可以在 JPQL 中使用 JOIN FETCH 语法来显式提取子集合。这有点像 EAGER 获取。
(3) 使用 OpenSessionInViewFilter
LazyInitializationException经常出现在视图层中。如果你使用Spring框架,你可以使用OpenSessionInViewFilter。但是,我不建议您这样做。如果使用不当,可能会导致性能问题。

我知道这是一个老问题,但我想提供帮助。
你可以把事务注释放在你需要的服务方法上,在这种情况下,findTopicByID(id)应该有
@Transactional(propagation=Propagation.REQUIRED, readOnly=true, noRollbackFor=Exception.class)
有关此注释的更多信息,请参阅此处
关于其他解决方案:
fetch = FetchType.EAGER
不是一个好的做法,它应该只在必要时使用。
Hibernate.initialize(topics.getComments());
休眠初始值设定项将类绑定到休眠技术。如果您的目标是灵活,这不是一个好方法。
希望对你有帮助
模板简介:该模板名称为【Java 如何解决“无法延迟初始化角色集合”休眠异常】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。