I have seen several people agonize over the Lazy Initialization Exception that appears when working with Spring MVC and Hibernate. I too have spent roughly the last 3 days trying to troubleshoot the problem, and I believe I have found a solution.
In several places, the recommended configuration for the session factory is:
DON'T DO THISCode:<bean id="sessionFactory" class="{Some session Factory class}"> <property name="dataSource" ref="dataSource" /> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean>
If you pay careful attention to your log during server startup, you will notice a curious line appear:
This entries that appear in the cfg.xml file are causing a separate null session factory to be created, which is causing trouble when the Object returned by a hibernate "get" and its properties are lazy loaded.Code:INFO: Configured SessionFactory: null
Instead, do not use the separate cfg.xml file. Put the annotated classes right in the session factory declaration, and change the sessionFactory class to AnnotationSessionFactoryBean
This whole thread assumes you are using annotations.
After I made this change, no more lazy load exceptions.Code:<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> {List of Annotated Classes} <value>{Class}</value> </list> </property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean>


Reply With Quote
