采用OpenSessionInViewFilter模式来管理事务的session

来源:互联网 发布:java redis zadd 编辑:程序博客网 时间:2024/05/16 17:12

    spring管理事务,事务的范围
   *  如果当前执行的方法没有事务环境,当this.getHibernateTemplate这个方法执行完以后
      session立即关闭
   *  如果当前执行的方法有事务环境,当事务环境的方法被调用完毕以后session关闭

 

在web.xml文件中:
    做了opensessioninview的配置
     从右边的代码可以看出来:
         当提交一个请求时,OpenSessionInView中已经把session
         开启了,在response以后才要关闭session
    也就意味着有了opensessioninview模式以后,session的打开被提前
  了,session的关闭被延后了,这样就解决了懒加载引起的异常
     两个过滤器,OpenSessionInview必须在struts2的过滤器之前


    缺点:
        因为session的关闭被延后了,而hibenate的一级缓存在session
     中,所以会导致大量的缓存中的数据被长时间停留在内存中

web.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name> 
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/applicationContext.xml</param-value>
 </context-param>
 <!-- opensessioninviewfilter让session开启提前,让session延后关闭,解决了懒加载引起的错误 -->
 <filter>
  <filter-name>OpenSessionInViewFilter</filter-name>
  <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>OpenSessionInViewFilter</filter-name>
  <url-pattern>*.action</url-pattern>
 </filter-mapping>
 
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

过滤器opensessioninviewfiter必须在strutsprepareandexecutefilter之前配置,否则不起作用

0 0
原创粉丝点击