org.hibernate.LazyInitializationException:懒得初始化一个角色集合(Hibernate + Spring)

时间:2011-08-09 17:20:09

标签: hibernate spring spring-mvc hibernate-mapping

我有一个带有以下文件的SpringMVC + Hibernate Web应用程序:

  

的applicationContext.xml

    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="org.postgresql.Driver"/>
    <property name="url" value="jdbc:postgresql://localhost:5432/db"/>
    <property name="username" value="kjhkjkj"/>
    <property name="password" value="dsfa@efe45"/>
</bean>

<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>

<bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="txManager"/>
    <property name="transactionAttributes">
        <props>
            <prop key="*">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
    <property name="target">
        <bean class="dao.DocumentViewDao">
            <property name="sessionFactory" ref="hibernateSessionFactory"/>
        </bean>
    </property>
    <property name="proxyTargetClass" value="true"/>
</bean>

<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
    <value>orm/Document.hbm.xml</value>
    <value>orm/UploadedDocument.hbm.xml</value>
    <!-- More resource files go here -->
        </list>
    </property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
            hibernate.show_sql = true
            hibernate.format_sql = true
            hibernate.generate_statistics = true
            hibernate.cache.use_query_cache = true
            hibernate.cache.use_second_level_cache = true
            hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
            hibernate.query.substitutions = true 't', false 'f'
        </value>
    </property>
</bean>

<bean id="documentViewDao" class="dao.DocumentViewDao">
    <property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
  

dao.DocumentViewDao

@Transactional
public class DocumentViewDao extends HibernateDaoSupport
{
public List all ( )
        throws HibernateException
{
    Session session = this.getSessionFactory ( ).getCurrentSession ( );

    return session.createQuery ( new StringBuilder ( 35 )
                    .append ( "SELECT d.id AS id, d.identifier AS identifier, d.title AS title, u.version AS version, u.effectFrom AS effectFrom " )
                    .append ( "FROM Document AS d " )
                    .append ( "LEFT OUTER JOIN d.uploadedDocumentsById AS u " )
                    .append ( "WITH u.isCurrent = true" )
                    .toString ( ) )
            .setCacheable ( true )
            .setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
            .list ( );
}

public Document getDocument ( int documentId )
        throws HibernateException
{
    Session session = this.getSessionFactory ( ).getCurrentSession ( );

    Document document = null;

    Query q = session.createQuery ( "FROM IsoDocument AS d " +
                                    "LEFT OUTER JOIN FETCH d.uploadedDocumentsById " +
                                    "WHERE d.id = :documentId"
    );
    q.setParameter ( "documentId", documentId );
    q.setCacheable ( true );
    document = ( Document ) q.uniqueResult ( );

    return document;
}
}
  

controller.DocumentController

public class DocumentController implements Controller
{   
    public ModelAndView handleRequest ( HttpServletRequest request, HttpServletResponse response )
            throws Exception
    {
        ModelAndView modelAndView = new ModelAndView ( "document" );

        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext ( );
        DocumentViewDao documentViewDao = ( DocumentViewDao ) context.getBean ( "transactionProxy" );

        Document document = DocumentViewDao.getDocument ( Integer.parseInt ( request.getParameter ( "id" ) ) );
        modelAndView.addObject ( "document", document );

        return modelAndView;
    }
}

ORM类和映射应该没问题,我不会写它们(丢失行:)) 所以问题是我得到了

  

org.hibernate.LazyInitializationException:懒得初始化一个角色集合:orm.Document.uploadedDocumentsById,没有关闭会话或会话

当controller.DocumentController生成的页面刷新时。显然,我无法解决的缓存和事务存在问题。而且,使用来自dao.DocumentViewDao的all()不会抛出这样的异常(但查询中没有FETCH)。所以你有什么想法吗?我也很乐意在orger中对此代码提出任何意见和/或建议以改进它(我是Spring和Hibernate的新手)。

1 个答案:

答案 0 :(得分:5)

当返回实体实例的查询是可缓存的并且您有缓存命中时,缓存只返回实体的ID,然后会话用于加载实体(ies) 。这意味着当您有缓存命中时,不再应用连接fecth。这也意味着查询返回的所有实体实例也应该位于二级缓存中,否则性能可能实际上比没有查询缓存更差。

因此,您应该在DAO中使用Hibernate.initialize(document.getUploadedDocumentsById()来确保它已初始化。