spring事务管理实例备注

2 篇文章 0 订阅
1 篇文章 0 订阅
web项目下使用spring框架进行事务管理,导入spring的相关jar包之后,在spring的配置文件中添加下列配置信息:
<!-- 使用JDBC事物 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" /><span style="font-family: Arial, Helvetica, sans-serif;"><!-- 数据源 --></span>
	</bean>

	<!-- AOP配置事物 需要监控的对数据库的操作方法-->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="del*"  propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="*" propagation="REQUIRED" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 配置AOP切面 扫面下面路径显得文件,有上面方法名称的方法全部加入管理-->
	<aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com..service.*.*(..))"/>
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/>
    </aop:config>
	
	<!-- 使用annotation注解方式配置事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />

在上面的切面扫描路径下添加对应的方法,如:
<pre name="code" class="java">@Override
	public void add() throws Exception {
		
		String msg = ..dao.add();
		//
		if(!"success".equals(<span style="font-family:Arial, Helvetica, sans-serif;">msg</span>)){
			throw new RuntimeException(retMsg);
		}
	}
默认情况下spring只对运行时异常会触发事务回滚,所以如果想自定义抛出异常时必须抛出RuntimeException异常,抛出Exception不会回滚。
 

如果想抛出任何异常都事务回滚,可以在事务配置的扫描方法里添加配置,如下:<pre name="code" class="html"><tx:method name="*" read-only="false" rollback-for="java.lang.Exception"/>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值