在用hibernate 4的时候会出现org.hibernate.LazyInitializationException: could not initialize proxy - no Session 网上出现最多的解决方案是 openSessionInViewFilter,但是在用了openSessionInViewFilter之后还是会在级联对象的时候出现这个错误,最后到网上查,好不容易查到了一个解法,在设置了openSessionInViewFilter之后,还需要在spring中hibernate相关配置文件中的sessionFactory配置了另外一个参数: ( 在stackoverflow 上面找到一篇介绍 ) hibernate.enable_lazy_load_no_trans 的处理,配置后解决了错误:
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="packagesToScan">
- <list>
- <value>com.alexgaoyh</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="javax.persistence.validation.mode">none</prop>
- <prop key="hibernate.dialect">${hibernate.dialect}</prop>
- <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
- <prop key="hibernate.format_sql">true</prop>
- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
- <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
- <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
- <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
- <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
- <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>
- <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
- </props>
- </property>
- </bean>