I am using Hibernate\'s lazy loading, and am getting sessionFactory missing exception, even after I have defined a filter in web.xml to use OpenSessionInViewFilter
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
.
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.
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" />