spring的事务配置

事务处理需要新增命名空间:

	xmlns:tx="http://www.springframework.org/schema/tx"
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
aop需要新增命名空间:
	xmlns:aop="http://www.springframework.org/schema/aop" 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 

都需要配置事务管理器:

	<!-- 事务管理器  -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>


一. 声命式事务处理,不使用aop

1.  配置命名空间, 打开事务注解驱动

2. 配置事务管理器, 且bean的id一定要为transactionManager

3. 在service或者dao实现类上(需要使用事务的地方)标注事务注解@Transactional

applicationContext.xml配置:

		
	<!-- 事务注解驱动 -->
	<tx:annotation-driven />
	


Java代码:

package com.changez.sm.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.changez.sm.bean.User;
import com.changez.sm.mapper.UserMapper;
import com.changez.sm.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userMapper;
	
	@Override
	public void insertUser(User user, User user1) {
		userMapper.insertUser(user);
		int a = 4/0; //测试事务,要么全部成功, 要么全部失败
		userMapper.insertUser(user1);
	}
}

二. 声明式事务处理, 使用aop:

1.配置aop切面, 切入点,通知等信息

2. 配置通知中事务传播行为等信息

3. 由切入点自行匹配需要添加事务的方法, 所以在不需要使用@Transactional注解

	
	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
<!--  			传播行为 , method:通过正则表达式匹配需要添加事务的方法 -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
<!-- 	aop -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.changez.sm.service.impl.*.*(..))"/>
	</aop:config>




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值