spring事务管理
4304 点击·0 回帖
![]() | ![]() | |
![]() | 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 | |
![]() | ![]() |