【问题标题】:LazyInitializationException on eagerly fetched (detached) collectionLazyInitializationException 急切地获取(分离)集合
【发布时间】:2012-08-27 20:29:06
【问题描述】:

首先是一些信息:

  • 我正在使用:
    • 春季 3.1.1.RELEASE
    • 休眠 4.1.5.SP1
    • JSF 2.0?
    • OpenSessionInViewFilter (org.springframework.orm.hibernate4.support.OpenSessionInViewFilter)
    • PrimeFaces 3.3.1
    • 龙目岛 0.11.2
    • JBoss 7.1.1.Final

简短版:

当我的实体Emloyee 分离时(因此它也急切地获取Locations 的集合),我不能在没有LazyInitializationException 的情况下调用Employee.getLocations().add()。使用基于非 JPA 的集合作为传输对象是可行的。

长版:

我有一个实体Employee,它有一个Locations 的集合:

@Data
@EqualsAndHashCode(callSuper = true, of = {})
@ToString(callSuper = true, of = {})
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee extends Person
{
    @ManyToMany
    @JoinTable(name = "location_employee",
            joinColumns = @JoinColumn(name = "employee_id",
                    referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "location_id",
                    referencedColumnName = "id"))
    private Set<Location>   locations   = new HashSet<Location>();
}

Employee 扩展自 Person,其中包含一些字符串,例如名称等,但这些不相关。

@Data
@EqualsAndHashCode(of = "id")
@ToString(of = { "id", "name" })
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Setter(AccessLevel.NONE)
    private Long    id;

    private String  name;
}

Location 类也很简单:

@Data
@EqualsAndHashCode(of = "id")
@ToString(of = { "id", "name" })
@Entity
public class Location
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Setter(AccessLevel.NONE)
    private Long            id;

    private String          name;
    @ManyToMany
    @JoinTable(name = "location_employee",
            joinColumns = @JoinColumn(name = "location_id",
                    referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "employee_id",
                    referencedColumnName = "id"))
    private Set<Employee>   employees = new HashSet<Employee>();
}

默认情况下所有集合都是惰性的。但是在我的 JSF 页面中,我想将 Locations 添加到现有的 Employee。为此,我渴望使用以下支持 bean 加载我的 Employee

@Named
@Scope("view")
public class BackingBean
{
    @Inject
    private EmployeeDAO employeeDAO;
    private Employee        employeeFull;
    @Inject
    private LocationDAO locationDAO;
    private List<Location> locations;

    public Employee getSelectedEmployeeFull()
    {
        if (selectedEmployeeFull == null)
        {
            selectedEmployeeFull = employeeDAO.getEagerById(1L);
        }
        return selectedEmployeeFull;
    }

    public void setEmployeeFull(Employee e)
    {
        employeeFull = e;
    }

    public List<Location> getLocations()
    {
        if (locations == null)
        {
            locations = locationDAO.getAll()
        }
        return locations;
    }

    //...
} 

EmployeeDAO 类包括急切加载查询:

@Named
public class EmployeeDAO
{
    @Inject
    private SessionFactory sessionFactory;

    @Transactional(readOnly = true)
    public Employee getEager(Long id)
    {
        Query q = sessionFactory.getCurrentSession().createQuery("select e from Employee e join fetch e.locations where e.id = :id");
        q.setParameter("id", id);
        try
        {
            return (Employee) q.uniqueResult();
        }
        catch (NonUniqueObjectException ex)
        {
            //Exception logging/handling
            return null;
        }
    }
}

在我的 JSF 中,我有以下 sn-p:

<p:dialog dynamic="true">
    <h:form>
        <p:selectCheckboxMenu label="Locations" value="#{employeeBean.employeeFull.locations}">
            <f:selectItems var="location" itemLabel="#{location.name}" value="#{employeeBean.locations}" />
        </p:selectCheckboxMenu>

        <p:commandButton value="save" action="#{employeeBean.update}"/>
    </h:form>
</p:dialog>

当我打开对话框时,它会很好地加载employeeFull 属性,并用Locations 填充selectCheckboxMenu,并将Locations 标记为Employee 已经拥有。

但是,当我单击保存按钮(不做任何更改)并提交表单时,Employee.locations 集合会出现 LazyInitializationException

09:36:42,633 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http-localhost-127.0.0.1-8080-1) failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:394) [hibernate-core-4.1.5.SP1.jar:4.1.5.SP1]
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:386) [hibernate-core-4.1.5.SP1.jar:4.1.5.SP1]
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:379) [hibernate-core-4.1.5.SP1.jar:4.1.5.SP1]
    at org.hibernate.collection.internal.PersistentSet.add(PersistentSet.java:206) [hibernate-core-4.1.5.SP1.jar:4.1.5.SP1]
    at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValuesForModel(MenuRenderer.java:382) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectManyValue(MenuRenderer.java:129) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:315) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at org.primefaces.component.selectcheckboxmenu.SelectCheckboxMenuRenderer.getConvertedValue(SelectCheckboxMenuRenderer.java:34) [primefaces-3.3.1.jar:]
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIInput.validate(UIInput.java:960) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1233) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIInput.processValidators(UIInput.java:698) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIForm.processValidators(UIForm.java:253) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at org.primefaces.component.dialog.Dialog.processValidators(Dialog.java:359) [primefaces-3.3.1.jar:]
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79) [primefaces-3.3.1.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:322) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:184) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:155) [spring-security-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) [spring-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:119) [spring-orm-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) [spring-web-3.1.1.RELEASE.jar:3.1.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_31]

EmployeeBean.update 方法永远不会被调用,因为它上设置的断点永远不会被命中。

现在是大结局:我该如何防止LazyInitializationException

编辑

我已经创建了一个解决方法,但这可能不是最好的解决方案:

在 JSF 页面中:

<p:dialog dynamic="true" onShow="loadSelectedEmployee()">
    <h:form>
        <p:remoteCommand action="#{employeeBean.loadSelectedEmployee}" name="loadSelectedEmployee" update=":editEmployeeDialogContent" />
    </h:form>
    <p:outputPanel layout="block" id="editEmployeeDialogContent">
        <h:form rendered="#{employeeBean.selectedEmployeeLoaded}">
            <p:selectCheckboxMenu label="Locations" value="#{employeeBean.selectedEmployee.locations}">
                <f:selectItems var="location" itemLabel="#{location.name}" value="#{employeeBean.locations}" />
            </p:selectCheckboxMenu>

            <p:commandButton value="save" action="#{employeeBean.update}"/>
        </h:form>
    </p:outputPanel>
</p:dialog>

在后台bean中:

public void loadSelectedEmployee()
{
    if (!selectedEmployeeLoaded)
    {
        selectedEmployee.setLocations(locationManager
                .getByEmployee(selectedEmployee));
        selectedEmployee.setRoles(roleManager
                .getByEmployee(selectedEmployee));
        selectedEmployeeLoaded = true;
    }
}

【问题讨论】:

  • 尝试通过删除转换器等不必要的东西来追踪问题。
  • @JMelnik 我删除了转换器,堆栈跟踪仅从第 4 行到第 12 行不同。当包断开连接时 JSF 调用 PersistentBag.add() 方法时,问题就出现了。
  • 尝试使用休眠检查集合是否已初始化,将其放在代码中的某个位置(查看堆栈跟踪)。如何查看:stackoverflow.com/a/4306498/685962
  • @JMelnik 执行急切查询时,我看到使用连接获取位置集合。然后当我在集合上调用Hibernate.isInitialized() 时,它返回true。不会触发其他查询。顺便说一句,使用非 JPA 集合是可行的(我会在几秒钟内更新我的问题)。
  • 这可能是不必要的,但也尝试将 Set 更改为 Collection = ArrayList

标签: ajax hibernate jpa primefaces lazy-initialization


【解决方案1】:

这绝对是一个错误,我猜是在 Primefaces 或 Jboss-jsf-api-2.1 中。 我可以直接在控制器中修改 PersistenSet,因此它肯定会立即加载,但是当绑定到 JSF 组件(我使用 Primefaces selectCheckboxMenu)时,它也会抛出 LazyInitalizationException。

【讨论】:

    【解决方案2】:

    如果您对与标记为“eager”没有关系的实体执行 HQL,将继续使用“lazy”的品牌并尝试在“get”时查询数据。

    对于这种情况,强制初始化关系的示例是:

    Hibernate.initialize(e.getLocations());
    

    综合:

    @Transactional(readOnly = true)
    public Employee getEager(Long id)
    {
        Query q = sessionFactory.getCurrentSession().createQuery("select e from Employee e join fetch e.locations where e.id = :id");
        q.setParameter("id", id);
        try
        {
            final Employee e = (Employee) q.uniqueResult();
            if(e != null){
                Hibernate.initialize(e.getLocations());
            }
            return e;
    
        }
        catch (NonUniqueObjectException ex)
        {
            //Exception logging/handling
            return null;
        }
    }
    

    问候,

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2012-12-17
      • 2023-03-24
      • 1970-01-01
      • 2016-02-19
      • 2011-08-14
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多