延迟加载错误

时间:2010-12-05 10:59:07

标签: hibernate transactions java-ee spring-mvc lazy-loading

我知道这个问题已经在这里提出了几次。但是我找不到任何有用的解决方案,所以我决定再次发布。

我正在使用Hibernate和Spring MVC框架,我正在尝试用子类获取我的类:

public class Scene implements Serializable{
private Long id;
private Author author;
//omitting getters and setters
} 

public class Author{
private Long id;
Private String  name; 
//omitting getters and setters
}

我的Hibernate配置如下:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="org.postgresql.Driver" />
  <property name="url" value="jdbc:postgresql://127.0.0.1/doolloop2" />
  <property name="username" value="doolloop2" />
  <property name="password" value="doolloop" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
     <property name="mappingLocations">
      <list>
        <value>WEB-INF/mapping/Scene.hbm.xml</value>
        <value>WEB-INF/mapping/Author.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
 <props>
  <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> 
  <prop key="hibernate.show_sql">true</prop> 
  <prop key="hibernate.hbm2ddl.auto">update</prop> 
  <prop key="hibernate.cache.use_second_level_cache">true</prop> 
  <prop key="hibernate.cache.use_query_cache">true</prop> 
  <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
  </props>
  </property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="txService" class="com.doolloop.services.TxDataBaseServiceImpl">
        <property name="sessionFactory">
        <ref local="sessionFactory"/>
        </property>
    </bean> 

现在我有了获取场景的方法:

@Override
    @Transactional(readOnly = true)
    public Scene getScene(Long id) {
        Session session = this.sessionFactory.getCurrentSession();
        Query q = session.createQuery("select scene from com.doolloop.objects.Scene scene where scene.id=:id");
        q.setLong("id", id);
        Scene scene = (Scene)q.uniqueResult()
        return scene;

    }

和我的春季mvc代码:

 @RequestMapping(value="/getSceneMetaData.dlp",method = RequestMethod.GET)
     @ResponseBody
     public Scene getSceneMetaData(@RequestParam String id){
        Scene scene = service.getScene(Long.parseLong(id));
        return scene;
    }

当我执行它时,我得到了以下例外:

Dec 5, 2010 12:29:21 PM org.hibernate.LazyInitializationException <init>
    SEVERE: failed to lazily initialize a collection of role: com.doolloop.objects.Scene.author, no session or session was closed
    org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.doolloop.objects.Scene.vauthor, no session or session was closed

我用谷歌搜索并理解它发生的原因是它在Transaction关闭时尝试获取作者并且默认情况下作者类是惰性的,但是我无法理解的是我应该如何修改我的代码以便解决它。

任何建议都受到欢迎。

UPD:这是两个类的映射文件:

<class
        name="com.doolloop.objects.Scene"
        table="scene"
    >
        <id
            name="id"
            column="Id"
            type="java.lang.Long"
            unsaved-value="null"
        >
         <generator class="sequence">
                <param name="sequence">doolloop2.sceneseq</param>
            </generator>
        </id>
    <many-to-one
         name="author"
         class="com.doolloop.objects.Author"
         cascade="all"
         column="authorid"
         unique="false"
     />  
    </class>

<hibernate-mapping>
    <class
        name="com.doolloop.objects.Author"
        table="authors"
    >
        <id
            name="id"
            column="Id"
            type="java.lang.Long"
            unsaved-value="null"
        >
         <generator class="sequence">
                <param name="sequence">doolloop2.authorseq</param>
            </generator>
        </id>
        <property
            name="name"
            update="true"
            insert="true"
            not-null="false"
            unique="false"
            type="java.lang.String"
        >
            <column name="name" />
        </property>
             <property
            name="email"
            update="true"
            insert="true"
            not-null="false"
            unique="false"
            type="java.lang.String"
        >
            <column name="email" />
        </property>
        <property
            name="site"
            update="true"
            insert="true"
            not-null="false"
            unique="false"
            type="java.lang.String"
        >
            <column name="site" />
        </property>
       <property
            name="contactInfo"
            update="true"
            insert="true"
            not-null="false"
            unique="false"
            type="java.lang.String"
        >
            <column name="contactInfo" />
        </property>
    </class>

UPD2 我在web.xml中添加了以下内容:

 <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
  <filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/getSceneMetaData.dlp</url-pattern>
</filter-mapping>

它给了我以下例外:

org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.doolloop.objects.Scene["author"]->com.doolloop.objects.Author_$$_javassist_4["name"])

UPDATE3:

这是此操作的log4j输出:

2010-12-06 11:48:09,031 DEBUG [org.springframework.orm.hibernate3.support.OpenSessionInViewFilter] - Using SessionFactory 'sessionFactory' for OpenSessionInViewFilter
2010-12-06 11:48:09,036 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'sessionFactory'
2010-12-06 11:48:09,040 DEBUG [org.springframework.orm.hibernate3.support.OpenSessionInViewFilter] - Opening single Hibernate Session in OpenSessionInViewFilter
2010-12-06 11:48:09,042 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] - Opening Hibernate Session
2010-12-06 11:48:09,048 DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'doolloop' processing GET request for [/dlp/getSceneMetaData.dlp]
2010-12-06 11:48:09,056 DEBUG [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping] - Mapping [/getSceneMetaData.dlp] to HandlerExecutionChain with handler [com.doolloop.controllers.SceneController@21c33b55] and 2 interceptors
2010-12-06 11:48:09,060 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/dlp/getSceneMetaData.dlp] is: -1
2010-12-06 11:48:09,142 DEBUG [org.springframework.core.convert.support.GenericConversionService] - Converting value '140' of [TypeDescriptor java.lang.String] to [TypeDescriptor @org.springframework.web.bind.annotation.RequestParam java.lang.String]
2010-12-06 11:48:09,146 DEBUG [org.springframework.core.convert.support.GenericConversionService] - Converted to '140'
2010-12-06 11:48:09,148 DEBUG [org.springframework.web.bind.annotation.support.HandlerMethodInvoker] - Invoking request handler method: public com.doolloop.objects.Scene com.doolloop.controllers.SceneController.getSceneMetaData(java.lang.String)
2010-12-06 11:48:16,401 DEBUG [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver] - Resolving exception from handler [com.doolloop.controllers.SceneController@21c33b55]: org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.doolloop.objects.Scene["author"]->com.doolloop.objects.Author_$$_javassist_4["name"])
2010-12-06 11:48:16,561 DEBUG [org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver] - Resolving exception from handler [com.doolloop.controllers.SceneController@21c33b55]: org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.doolloop.objects.Scene["author"]->com.doolloop.objects.Author_$$_javassist_4["name"])
2010-12-06 11:48:16,568 DEBUG [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] - Resolving exception from handler [com.doolloop.controllers.SceneController@21c33b55]: org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.doolloop.objects.Scene["author"]->com.doolloop.objects.Author_$$_javassist_4["name"])
2010-12-06 11:48:16,572 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Could not complete request
org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.doolloop.objects.Scene["author"]->com.doolloop.objects.Author_$$_javassist_4["name"])
    at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:215)

//// Entire stack trace goes here.

2010-12-06 11:48:16,660 DEBUG [org.springframework.orm.hibernate3.support.OpenSessionInViewFilter] - Closing single Hibernate Session in OpenSessionInViewFilter
2010-12-06 11:48:16,662 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] - Closing Hibernate Session

UPDATE4:

我只看到一个选择n控制台:

Hibernate: select scene0_.Id as Id20_0_, scene0_.name as name20_0_, scene0_.description as descript3_20_0_, scene0_.defaultView as defaultV4_20_0_, scene0_.authorid as authorid20_0_ from scene scene0_ where scene0_.Id=?

但是,如果我以这种方式修改我的getScene方法:

 public Scene getScene(Long id) {
        Session session = this.sessionFactory.getCurrentSession();
        Query q = session.createQuery("select scene from com.doolloop.objects.Scene scene where scene.id=:id");
        q.setLong("id", id);
        Scene scene = (Scene)q.uniqueResult()
        **Author author = scene.getAuthor();**
        return scene; 

我会看到第二个选择出现:

Hibernate: select author0_.Id as Id23_0_, author0_.name as name23_0_, author0_.email as email23_0_, author0_.site as site23_0_, author0_.contactInfo as contactI5_23_0_ from authors author0_ where author0_.Id=?

但作者对象仍然是空的。

从控制器调用相同的getter会导致异常。

1 个答案:

答案 0 :(得分:7)

首先发布Scene.hbm.xml和Author.hbm.xml可能是值得的。

从我在这里看到的: https://forum.hibernate.org/viewtopic.php?f=1&t=994772&start=0 如果使用注释,默认情况下会多次加载多对一关系,但是如果使用XML映射则不会发生这种情况!

我要说修改多对一关系并明确设置fetch="EAGER"

所以结果应该是:

<many-to-one
     name="author"
     class="com.doolloop.objects.Author"
     cascade="all"
     column="authorid"
     unique="false"
     fetch="EAGER"
 />  

你已经提到过你有两种使用场景:一种是你获取Scene对象而你需要它所有的依赖项,另一种是你只对id和几个字段感兴趣的场景。这似乎是定义Hibernate会话边界的问题。您可以使用此处描述的SessionInViewFilter:http://community.jboss.org/wiki/OpenSessioninView这样,Hibernate会话将在http请求期间打开,因此您将能够访问延迟加载的引用以获得时间。这有帮助吗?

=================================
我已经看到了你的OpenSessionInViewFilter定义 - 它可能值得明确设置你的HibernateSessionFactory的名字:

<filter>
   <filter-name>openSessionInViewFilter</filter-name>
   <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
     <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
     </init-param>
 </filter>

另外,我没有在Spring Config中看到您的Tx Manager正确初始化。仅仅定义它是不够的,你需要:

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

=================================
从我在Hibernate文档中看到的情况来看,很可能一旦你关闭事务,你的Hibernate会话就会结束(即使你使用的是OpenSessionInView过滤器)。 看看这里: http://community.jboss.org/wiki/OpenSessioninView#Can_I_commit_the_transaction_before_rendering_the_view

关闭事务后,数据库连接将返回到池中,并且对数据库的所有进一步访问都需要一个新连接,该连接应该具有自动提交模式。

但是,在您的情况下,我认为解决方案是确保您在事务仍处于打开状态时加载了从数据库加载所需的所有内容!