我有这样一个问题:

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


当前回答

我知道这是个老问题,但我想帮忙。 可以将事务注释放在所需的服务方法上,在本例中findTopicByID(id)应该具有

@Transactional(propagation=Propagation.REQUIRED, readOnly=true, noRollbackFor=Exception.class)

关于这个注释的更多信息可以在这里找到

关于其他解决方案:

fetch = FetchType.EAGER 

这不是一个好的做法,只有在必要时才应该使用。

Hibernate.initialize(topics.getComments());

hibernate初始化器将类绑定到hibernate技术。如果你的目标是灵活并不是一个好方法。

希望能有所帮助

其他回答

还有另一种方法,可以使用TransactionTemplate封装惰性获取。 就像

Collection<Comment> commentList = this.transactionTemplate.execute
(status -> topicById.getComments());

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

有两种解决方案。

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

详见我的帖子。

为了解决这个问题,在我的例子中,它只是少了这一行

<tx:annotation-driven transaction-manager="myTxManager" />

在应用程序上下文文件。

方法上的@Transactional注释没有考虑在内。

希望这个答案能帮助到一些人

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

@PersistenceContext(type = PersistenceContextType.EXTENDED)

这是我最近遇到的问题,我用

<f:attribute name="collectionType" value="java.util.ArrayList" />

这里有更详细的描述,这挽救了我的一天。