【问题标题】:How to retrieve a list of subentities如何检索子实体列表
【发布时间】:2012-04-01 02:28:46
【问题描述】:

org.hibernate.LazyInitializationException: 延迟初始化角色集合失败:com.siteadmin.domain.HostSite.sectionList,没有会话或会话被关闭

主机站点

@Entity
@Table(name="hs")
public class HostSite {
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO)  
    private Integer id;

    @OneToMany(mappedBy="hostSite")
    private List<HostSiteSection> sectionList;

主机站点部分

@Entity
@Table(name="hsst")
public class HostSiteSection {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="hsid")
    private HostSite hostSite;

控制器

screenObject.setSectionList(hostSite.getSectionList());

JSP

<c:if test="${screenObject!=null && screenObject.getSectionList()!=null}">
    <c:forEach items="${screenObject.getSectionList()}" var="section">
        <tr>
             <td><a href="../hostSiteSection/${section.id}" target="_blank">${section.id}</a></td>
             <td><a href="../hostSiteSection/${section.id}" target="_blank">${section.name}</a></td>        
             <td>${section.order}</td>
        </tr>
    </c:forEach>
</c:if>

它在哪里分崩离析?在控制器还是jsp?原因是什么?急切和懒惰我都试过了。

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    您需要在HostSite 中急切地加载集合sectionList

    @Entity
    @Table(name="hs")
    public class HostSite {
        @Id 
        @GeneratedValue(strategy = GenerationType.AUTO)  
        private Integer id;
    
        @OneToMany(mappedBy="hostSite",fetch=FetchType.EAGER)
        private List<HostSiteSection> sectionList;
    

    HQL API 文档reference

    【讨论】:

      【解决方案2】:

      问题是您的休眠会话在您的代码尝试检索列表时已关闭。如果您的实体因会话关闭并重新打开而不再附加到会话,也会发生这种情况。

      将列表映射为渴望可能会解决此问题,但这不是最佳解决方案。大量使用 Eager fetching 会导致 hibernate 出现严重的性能问题。

      更好的解决方案是确保休眠会话是打开的,并且在您使用它时您的实体已附加到它。通过为open-session-in-view 模式附加一个servlet 过滤器,这可能在您的情况下最容易处理。 performance fetching initialization 上的休眠文档部分也描述了处理该问题的其他可能方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多