灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3297回复:0

spring事务管理

楼主#
更多 发布于:2012-09-08 09:47


spring 用aop方式植入事务,也可以自己将事务管理对象注入到service层,但很明显,aop方式更灵活,更强大,用aop方式的spring事务管理后,在dao层就不再需要任何的hibernate事务了,在service 层调用Dao也不需要再去管事务的问题了,可以一心写逻辑就oK了,当service需要事务时只需要将spring 管理的事务aop切入这个service ,这个service就使用事务了。代码如下:
[html]
<?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"
    xsichemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    default-lazy-init="false">

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>  www.atcpu.com
    <aop:config>
        <aop:pointcut expression="execution(* org.vean.services.LogLoginService.*(..))" id="txcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txcut"/>
    </aop:config>
</beans>
这就是一个spring的事务管理,aop切到的方法都将具备事务的特性。
注意:使用事务必需提供一个SessionFactory这是毋庸置疑的,但使用hibernate事务时一般将Session绑定到线程,只需设置:hibernate.current_session_context_class=thread,
而使用spring 的事务时,就不是将Session绑定到线程了,而是将Session绑定的spring的一个管理Session的容器中,设置wei :hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext,
如果没有使用事务对应的Seesion绑定设置,程序就会报错~,因为如果是 启用spring事务时,那么spring就会向SpringSessionContext要Session,如果Session没有绑定到SpringSessionContext类中,结果可想而知了。
作者:vean_system

喜欢0 评分0
游客

返回顶部