我有这样一个问题:

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


当前回答

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

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

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

其他回答

模型类Topic中的集合注释是惰性加载的,如果你不使用fetch = FetchType注释它,这是默认的行为。热切的特别。

findTopicByID服务很可能正在使用无状态Hibernate会话。无状态会话没有第一级缓存,即没有持久性上下文。稍后,当您尝试迭代注释时,Hibernate将抛出异常。

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

解决方案可以是:

使用fetch = FetchType注释注释。急切的 @OneToMany(fetch = FetchType。mappedBy = "topic", cascade = CascadeType.ALL) private Collection<Comment> comments = new LinkedHashSet<Comment>(); 如果您仍然希望延迟加载注释,请使用Hibernate的有状态会话,这样您就可以在需要时获取注释。

根据我的经验,我有以下方法来解决著名的LazyInitializationException:

(1)使用Hibernate.initialize

Hibernate.initialize(topics.getComments());

(2)使用JOIN FETCH

您可以在JPQL中使用JOIN FETCH语法显式地取出子集合。这有点像EAGER取回。

3)使用OpenSessionInViewFilter

LazyInitializationException经常发生在视图层。如果你使用Spring框架,你可以使用OpenSessionInViewFilter。但是,我不建议你这样做。如果使用不当,可能会导致性能问题。

你的列表是惰性加载的,所以列表没有加载。 仅仅通过电话进入名单是不够的。 在Hibernate中使用。初始化以初始化列表。 如果不起作用,运行列表元素并调用Hibernate。初始化每一个。 这需要在从事务范围返回之前进行。 看看这篇文章。 搜寻-

Node n = // .. get the node
Hibernate.initialize(n); // initializes 'parent' similar to getParent.
Hibernate.initialize(n.getChildren()); // pass the lazy collection into the session 

在我的情况下,下面的代码是一个问题:

entityManager.detach(topicById);
topicById.getComments() // exception thrown

因为它从数据库中分离,当需要时Hibernate不再从字段中检索list。所以我在分离之前初始化它:

Hibernate.initialize(topicById.getComments());
entityManager.detach(topicById);
topicById.getComments() // works like a charm

处理LazyInitializationException的最好方法是在查询时加入取回,像这样:

select t
from Topic t
left join fetch t.comments

您应该始终避免以下反模式:

FetchType。急切的 OSIV (Open Session in View) 冬眠。enable_lazy_load_no_trans Hibernate配置属性

因此,确保你的FetchType。LAZY关联在查询时或使用Hibernate在原始的@Transactional范围内初始化。初始化辅助集合。