Hibernate LAZY fetch [重复]

Posted

技术标签:

【中文标题】Hibernate LAZY fetch [重复]【英文标题】:Hibernate LAZY fetch [duplicate] 【发布时间】:2015-05-08 00:53:06 【问题描述】:

我在使用 Hibernate 和 LAZY fetch 时遇到问题。我有 Spring+Hibernate 应用程序。当我使用 EAGER fetch 时没问题,但是当我将 fetch 更改为 LAZY 时,它会抛出 org.hibernate.LazyInitializationException

型号

父请求

   import java.io.Serializable;
    import java.util.Objects;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;

    @Entity(name = "PARENT_REQUEST")
    @Table(name = "PARENT_REQUEST")
    public class ParentRequest implements Serializable

        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name="parent_id",nullable = false)
        private Parent parent;

        public ParentRequest() 
        
//getter setters..

父母

import java.util.Set;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import org.hibernate.collection.PersistentSet;

@Entity(name = "PARENT")
@DiscriminatorValue("par")
public class Parent extends User 

    public final static String ROLE_NAME = "par";

    //private Set<Student> students;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    private Set<ParentRequest> parentRequests = new HashSet();

    public Parent() 
    

//getters, setters

springContext.xml 中的休眠配置

  <bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>model.ParentRequest</value>
                <value>model.Parent</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.mysqlDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

dataSource bean 配置良好。

这是 JUnit 测试的堆栈跟踪:

failed to lazily initialize a collection of role: model.Parent.parentRequests, no session or session was closed
org.hibernate.LazyInitializationException
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
    at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
    at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
    at org.hibernate.collection.PersistentSet.size(PersistentSet.java:162)
    at dao.impl.UserHibernateDAOTest.testSetParentReq_Parent(UserHibernateDAOTest.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)

我使用 Spring 4.1.5.RELEASE 和 Hibernate 3.6.10.Final。

谢谢!

【问题讨论】:

您发布的所有代码都运行良好。相关部分是您对这些实体进行操作的业务代码。确保对 parent 和 parentrequest 的这些操作发生在单个事务中。 【参考方案1】:

您正在尝试在会话关闭后访问惰性集合。阅读this。您可以在对象第一次访问时获取集合或保持会话

更新:你也可以查看this

【讨论】:

以上是关于Hibernate LAZY fetch [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate 5.2.9:@Basic(fetch = FetchType.LAZY) 不工作

Hibernate中fetch和lazy介绍

Hibernate中fetch和lazy介绍

Hibernate - lazy, fetch, inverse, cascade

hibernate/jpa 忽略 @XxxToOne 关系中的 LAZY FETCHING

Fetch Type LAZY 仍然会导致 Eager 加载 Hibernate Spring 数据