我有这样一个问题:

org.hibernate.LazyInitializationException:惰性初始化role: 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 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循环的行中


当前回答

对于fetch = FetchType.LAZY,你应该有两个东西。

@Transactional

and

Hibernate.initialize(topicById.getComments());

其他回答

原因是当您使用延迟加载时,会话是关闭的。

有两种解决方案。

不要使用惰性加载。 在XML中设置lazy=false或在注释中设置@OneToMany(fetch = FetchType.EAGER)。 使用惰性加载。 在XML中设置lazy=true或在注释中设置@OneToMany(fetch = FetchType.LAZY)。 并在web.xml中添加OpenSessionInViewFilter过滤器

详见我的帖子。

如果你知道你想在每次检索主题时看到所有的注释,那么将注释的字段映射更改为:

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

默认情况下,集合是惰性加载的,如果你想了解更多,可以看看这个。

这是一个老问题,但下面的信息可以帮助人们寻找答案。

@VladMihalcea的回答很有用。你不能依赖FetchType。相反,您应该在需要时将注释加载到Topic实体中。

如果您没有显式地定义您的查询以便您可以指定连接获取,那么使用@NamedEntityGraph和@EntityGraph您可以覆盖FetchType。LAZY(默认情况下@OneToMany关联使用LAZY)在运行时加载注释,只在需要时加载Topic。这意味着您将注释的加载限制在那些真正需要注释的方法(查询)上。JPA定义的实体图:

实体图可以与find方法一起使用,也可以作为查询提示 覆盖或增强FetchType语义。

您可以基于这里的JPA示例使用它。或者,如果您使用Spring Data JPA,那么您可以基于Spring提供的示例来使用它。

我发现将@PersistenceContext声明为EXTENDED也解决了这个问题:

@PersistenceContext(type = PersistenceContextType.EXTENDED)

在我的例子中,我有b/w A和b的映射

一个有

@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
Set<B> bs;

在DAO层中,如果您还没有使用Fetch Type - Eager对映射进行注释,则该方法需要使用@Transactional进行注释