我有这样一个问题:

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


当前回答

不是最好的解决方案,但对于那些面临LazyInitializationException的人,特别是在序列化上,这将有所帮助。在这里,您将检查惰性初始化属性并将其设置为null。为此,创建以下类

public class RepositoryUtil {
    public static final boolean isCollectionInitialized(Collection<?> collection) {
        if (collection instanceof PersistentCollection)
            return ((PersistentCollection) collection).wasInitialized();
        else 
            return true;
    }   
}

在你的实体类中,你有一个惰性初始化的属性,添加如下所示的方法。在这个方法中添加所有延迟加载属性。

public void checkLazyIntialzation() {
    if (!RepositoryUtil.isCollectionInitialized(yourlazyproperty)) {
        yourlazyproperty= null;
    }

在加载数据的所有位置之后调用这个checklazyinitialize()方法。

 YourEntity obj= entityManager.find(YourEntity.class,1L);
  obj.checkLazyIntialzation();

其他回答

对于这个惰性初始化问题有多种解决方案

1)将关联Fetch类型从LAZY更改为EAGER,但这不是一个好的做法,因为这会降低性能。

2)使用FetchType。在关联对象上使用LAZY,并在您的服务层方法中使用Transactional注释,以便会话保持打开状态,并且当您调用topicById.getComments()时,子对象(注释)将被加载。

3)另外,在控制器层请尽量使用DTO对象而不是实体。在你的例子中,会话在控制器层被关闭。所以最好在服务层将实体转换为DTO。

模型类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的有状态会话,这样您就可以在需要时获取注释。

对于那些使用Criteria的人,我发现

criteria.setFetchMode("lazily_fetched_member", FetchMode.EAGER);

我该做的都做了

集合的初始获取模式设置为FetchMode。LAZY提供性能,但当我需要数据时,我只需要添加这一行,并享受完全填充的对象。

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

@Transactional

and

Hibernate.initialize(topicById.getComments());

最好的解决方案之一是在应用程序中添加以下内容。属性文件: spring.jpa.properties.hibernate.enable_lazy_load_no_trans = true