spring进阶(二)事务

本文介绍了Spring框架中的事务管理机制,包括事务回滚的条件、事务配置的方法及如何通过AOP实现事务控制。重点讲解了在Service层配置事务,并强调了异常处理对于事务回滚的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. spring事务的回滚

    spring的事务,一般配置在service层

    spring事务中,不能使用try{...}catch{.....},否则不会发生回滚

     service层抛出的异常,必须是RunTimeException或者其它子类的异常,否则不会发生回滚

示例:

public void save() throws Exception{
		User user = new User() ;
		user.setId("111111") ;
		user.setName("xiaoming") ;
		user.setPassword("password") ;
		userMapper.insert(user) ; 
		save2();
	}
	
	public void save2() throws Exception{
		User user1 = new User() ;
		user1.setId("222222") ;
		user1.setName("xiaoxi") ;
		user1.setPassword("2222222222") ;
		if(1!=3){
			throw new RuntimeException();
		}
		userMapper.insert(user1) ;
	}


2. spring事务的配置文件

<?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-4.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
           http://www.springframework.org/schema/aop      
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 	   
           ">
	<!--  配置事务管理器,配置切面,配置切面的行为 -->
	
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 通知 
	               切面的行为,下面配置切面
	 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 传播行为 -->
			<tx:method name="save*" propagation="REQUIRED" /><!-- 在事务中执行 -->
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" /><!-- 有事务,在事务中执行,没有的话,不会开启新的事务 -->
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 配置切面 -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* com.whir.springmvc.service.*.*(..))" />
	</aop:config>
	

</beans>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值