Spring事务托管配置及session控制

一、   applicationContext_Transaction.xml的配置(事务配置)

<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd

    http://www.springframework.org/schema/tx

    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd

    http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<!-- 事务管理 -->

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <property name="sessionFactory">

            <ref bean ="sessionFactory" />

       </property>

    </bean>

     <tx:advice id="transAdvice" transaction-manager="transactionManager">

        <tx:attributes>

           <tx:method name="get*" read-only="true"/>

           <tx:method name="load*" read-only="true"/>

           <tx:method name="find*" read-only="true"/>

           <tx:method name="save*" propagation="REQUIRED"/>

           <tx:method name="update*" propagation="REQUIRED"/>

           <tx:method name="del*" propagation="REQUIRED"/>

           <tx:method name="remove*" propagation="REQUIRED"/>

           <tx:method name="*"/>

        </tx:attributes>

     </tx:advice>

     <aop:config><!—托管com.zxl.core.ICore接口中所有方法的事务-->

        <aop:pointcut id="transPoint"  expression=" execution(* com.zxl.core.ICore.*(..))" />

        <aop:advisor  advice-ref="transAdvice" pointcut-ref="transPoint" />      

     </aop:config>

     <aop:config><!—托管com.zxl.web.financemgr.services.impl包下所有方法的事务-->

        <aop:pointcut id="financeTrans"  expression=" execution(* com.zxl.web.financemgr.services.impl.*.*(..))" />

        <aop:advisor advice-ref="transAdvice" pointcut-ref="financeTrans"/>

     </aop:config>

</beans>

 

二、 web.xml 的配置

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <display-name>struts2</display-name>

  <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>*.action</url-pattern>

  </filter-mapping>

  <filter-mapping>

    <filter-name>struts2</filter-name>

    <url-pattern>*.jsp</url-pattern>

  </filter-mapping>

 

  <!-- 防止内存泄漏 -->

  <listener>

    <listener-class>

org.springframework.web.util.IntrospectorCleanupListener

</listener-class>

  </listener>

 

  <!-- Spring 配置开始 -->

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value><!--spring所有的配置文件-->

        classpath*:applicationContext_Business.xml,

        classpath*:applicationContext_Core.xml,

        classpath*:applicationContext_Hibernate.xml,

        classpath*:applicationContext_Service.xml,

        classpath*:applicationContext_Transaction.xml

    </param-value>

  </context-param>

  <listener>

    <listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

  </listener>

  <!-- Spring 配置结束 -->

 

  <!----------定义spring对xfire的服务控制器-------------------->

  <servlet>  

     <servlet-name>xfire</servlet-name>  

     <servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

  </servlet>

 

  <servlet-mapping>

     <servlet-name>xfire</servlet-name>

     <url-pattern>*.ws</url-pattern>

  </servlet-mapping>

 

  <!-----------定义xfire服务请求控制器----------------------->

  <servlet>

    <servlet-name>xfireServlet</servlet-name>

    <servlet-class>

org.codehaus.xfire.spring.XFireSpringServlet

</servlet-class>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>xfireServlet</servlet-name> 

    <url-pattern>/services/*</url-pattern>

  </servlet-mapping>

<!-- xfire 配置结束 -->

 

</web-app>

 

 

三、   Spring与Hibernate集成后对session的控制

 

1.通过getSession()方法获得session进行操作:

     public class Test  extends HibernateDaoSupport{  

       public void save(User user){  

          this.getSession().save(user);  

       }  

   }  

利用这种方式获得的session在方法执行结束之后不会自动关闭连接,我们必须通session.close() 或者releaseSession(session)来手动进行关闭,否则会造成内存泄露或者连接耗尽等问题。手动关闭session的 Java代码如下:

 public class Test  extends HibernateDaoSupport{  

     public void save(User user){  

          Session session = this.getSession();  

          session.save(user);  

          session.close();  

          // releaseSession(session);

       }  

   }   

如果对上述方法进行事务控制,那么spring框架会自动为我们关闭session,此种情况下再执行上述代码,会抛出如下异常:

1.   org.springframework.orm.hibernate3.HibernateSystemException: Session is closed; nested exception is org.hibernate.SessionException: Session is closed  

2.  …  

3.  org.hibernate.SessionException: Session is closed  

提示session已经关闭。但是如果在代码中通过releaseSession(session)的方法来关闭session,则不会抛出异常。releaseSession(session)方法的代码如下: 

 protected final void releaseSession(Session session) {  

   SessionFactoryUtils.releaseSession(session, getSessionFactory());  

  }  

它是通过SessionFactoryUtils的releaseSession方法来实现的,代码如下:

 public static void releaseSession(Session session,

                                         SessionFactory sessionFactory) {

    if (session == null) { return; }

     // Only close non-transactional Sessions.

    if (!isSessionTransactional(session,sessionFactory)){

         closeSessionOrRegisterDeferredClose(session, sessionFactory);

    }  

 }  

内部会先进行判断。getSession()方法的源码: 

 protected final Session getSession()  

   throws DataAccessResourceFailureException, IllegalStateException {  

      return getSession(this.hibernateTemplate.isAllowCreate());  

 }  

getSession()方法内部通过它的一个重载方法getSession(boolean allowCreate )来实现,变量allowCreate是HibernateTemplate中的变量,默认值为true,也就是创建一个新的session。如果调用getSession(false)来获得session,那么必须对其进行事务控制,原因是:(spring文档)

 protected  final  org.hibernate.Session  getSession()   

  throws DataAccessResourceFailureException,   IllegalStateException    

  Get a Hibernate Session, either from the current transaction or a new one. The latter is only allowed if the "allowCreate" setting of this bean's HibernateTemplate is true.   

getSession()方法从当前事务或者一个新的事务中获得session,如果想从一个新的事务中获得session(也就意味着当其不存在事务控制),则必须使HibernateTemplate中的allowCreate变量的值为”true”,而现在设置allowCreate变量的值为”false”就意味着无法从新的事务中获得session,也就是只能从当前事务中获取,所以必须对当前方法进行事务控制,否则会抛出如下异常:

  java.lang.IllegalStateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here ...  

同时,如果对getSession()所在的方法进行事务控制,那么类似如下的代码: 

 Session session = null;  

  for(int m =0;m<5;m++){  

     Admin admin = new Admin();  

    admin.setName("test");  

      admin.setPassword("098");     

    session = this.getSession();  

    session.save(admin);  

  }  

则只会打开一个session,因为事务控制必须确保是同一个连接,spring会确保在整个相关方法中只存在一个session。Spring在方法开始时会打开一个session(即使进行事务控制的方法内部不执行数据库操作),之后在请求session时,如果在事务中存在一个未commit的session就返回,以此确保同一个session。 

 

2.getCurrentSession()与openSession() 

getCurrentSession()与openSession()方法通过Hibernate的SessionFactory获得,两者的区别网上有很多文章已经介绍过,即:

 ①getCurrentSession创建的session会和绑定到当前线程,而openSession不会。   

  ②getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭  

对于getCurrentSession()方法: 
        (1)其所在方法必须进行事务控制 
        (2)Session在第一次被使用的时候,或者第一次调用getCurrentSession()的时候,其生命周期就开始。然后它被Hibernate绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate也会把Session从当前线程剥离,并且关闭它。假若你再次调用getCurrentSession(),你会得到一个新的Session,并且开始一个新的工作单元。     
   
对于openSession()方法: 
     这个方法一般在spring与Hibernate的集成中不直接使用,它就是打开一个session,并且这个  session与上下文无关,如果对其所在方法进行事务控制,会发现不起作用,原因就是前面提到的,事务控制必须确保是同一个连接,而openSession()打开的session与上下文无关。这个方法与getSession(),getCurrentSession()以及getHibernateTemplate()等方法的区别在于:后面的几个方法spring可以对其进行控制,如果对它们所在的方法进行事务控制,spring可以确保是同一个连接,而openSession()方法,spring无法对其进行控制,所以事务也不会起作用。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值