<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这个过滤器的作用是将hibernate的session的关闭延长到视图层,即事务的范围变大了,不是只在dao层或service层,而是延长到了
view层。好处就是在这段范围里hibernate的延迟加载一直都能用。比如:
public class Admin {
...
private Subject admin_Power; // 管理员权限
...
setter/getter...
}
public class Subject {
...
private String sub_name; // 科目名称
...
setter/getter...
}
<table border="1">
<s:iterator value="admin.admin_Power" status="st">
<tr>
<td><s:property value="#st.getIndex()+1"></s:property></td>
<td><s:property value="sub_name"></s:property></td>
</tr>
</s:iterator>
</table>
我们都知道hibernate默认延迟加载,在获得admin时它的admin_Power在事务中若不显示调用不会加载,这样节省内存。当我们把事
务放在dao或者service层时,在其中没有显示的调用admin_Power,这时在view层使用admin.admin_Power时就会说没有加载
admin_Power。报错:failed to lazily initialize a collection of role.
而使用了spring open in view,就可以解决这个问题了。
注:如果使用strut2的话这个过滤器要配置在FilterDispatcher的前面
-------------------------------------------------------------------------------------------------------------------------------
在没有使用Spring提供的Open Session In View情况下,因需要在service(or Dao)层里把session关闭,所以lazy loading 为true的话,要在应用层内把关系集合都初始化,如company.getEmployees(),否则Hibernate抛session already closed Exception。
Open Session In View提供了一种简便的方法,较好地解决了lazy loading问题。它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide),功能相同,只是一个在web.xml配置,另一个在application.xml配置而已。
Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。
OpenSessionInViewInterceptor配置:
<beans> <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor"/> </list> </property> <property name="mappings"> ...... </property> </bean> ...... </beans> OpenSessionInViewFilter配置: <web-app> ...... <filter> <filter-name>hibernateFilter</filter-name> <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter </filter-class> <!-- singleSession默认为true,若设为false则等于没用OpenSessionInView --> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> ...... <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> ...... </web-app>
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException { SessionFactory sessionFactory = lookupSessionFactory(); logger.debug("Opening Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); TransactionSynchronizationManager.bindResource( sessionFactory, new SessionHolder(session)); try { filterChain.doFilter(request, response); }finally { TransactionSynchronizationManager.unbindResource(sessionFactory); logger.debug("Closing Hibernate Session in OpenSessionInViewFilter"); closeSession(session, sessionFactory); } } protected Session getSession(SessionFactory sessionFactory)throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); session.setFlushMode(FlushMode.NEVER); return session; } protected void closeSession(Session session, SessionFactory sessionFactory)throws CleanupFailureDataAccessException { SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory); }
public static void closeSessionIfNecessary(Session session, SessionFactory sessionFactory)throws CleanupFailureDataAccessException { if (session == null || TransactionSynchronizationManager.hasResource(sessionFactory)){ return; } logger.debug("Closing Hibernate session"); try { session.close(); }catch (JDBCException ex) { // SQLException underneath throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex.getSQLException()); }catch (HibernateException ex) { throw new CleanupFailureDataAccessException("Could not close Hibernate session", ex); } }
<bean id="baseTransaction" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"/> <property name="proxyTargetClass" value="true"/> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="remove*">PROPAGATION_REQUIRED</prop> </props> </property> </bean>