Spring, Hibernate Lazy Loading, sessionFactory, and OpenSessionInViewFilter

独自空忆成欢 提交于 2019-11-29 12:20:18

You need to declare sessionFactory in the root web application context (i. e. /WEB-INF/spring/root-context.xml) to make it available to OpenSessionInViewFilter.

You have to put sesstionFactory Bean in your servlet-context.xml

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
    .....
</property>
<property name="hibernateProperties">
    ......
</property>
<property name="schemaUpdate" value="true" />

This is the code fragment inside the org.springframework.orm.hibernate3.support.OpenSessionInViewFilter class that looks up the sessionFactory bean :

/**
 * Look up the SessionFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the SessionFactory to use
 * @see #getSessionFactoryBeanName
 */
protected SessionFactory lookupSessionFactory() {
    if (logger.isDebugEnabled()) {
        logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
    }
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}

You'll notice that it uses the WebApplicationContextUtils class to load the session factory bean. The API (http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.html) for this class states :

Convenience methods for retrieving the root WebApplicationContext for a given ServletContext. This is useful for programmatically accessing a Spring application context from within custom web views or MVC actions.

Note that there are more convenient ways of accessing the root context for many web frameworks, either part of Spring or available as an external library. This helper class is just the most generic way to access the root context.

Thus you are required to declare the sessionFactory in the root context if you wish to use the Spring provided OpenSessionInViewFilter feature out of the box.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!