spring 事务管理

spring 用aop方式植入事务,也可以自己将事务管理对象注入到service层,但很明显,aop方式更灵活,更强大,用aop方式的spring事务管理后,在dao层就不再需要任何的hibernate事务了,在service 层调用Dao也不需要再去管事务的问题了,可以一心写逻辑就oK了,当service需要事务时只需要将spring 管理的事务aop切入这个service ,这个service就使用事务了。代码如下:

<?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-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>
	<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类中,结果可想而知了。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值