Spring aop 事务管理

spring.xml 增加如下配置

<!--数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
 		<property name="driverClassName" value="${jdbcDriver}" />
		<property name="url" value="${jdbcUrl}" />
		<property name="username" value="${jdbcUname}" />
		<property name="password" value="${jdbcUpwd}" />
 
 </bean>


 	<!-- 项目的事务管理 控制在service层 -->
    <!-- spring提供了声明式的事务管理器 -->
    <!-- 1:创建一个事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 引入数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 2:配置事务的传播特性 (增强类的增强效果),这一部分可以不加,加上比较保险-->
	<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="delete*" 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:attributes>
	</tx:advice>
	
	<!-- 配置切面 -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* com.ssm.service.impl.*.*(..))" />
	</aop:config>

使用 在servlice层引入@Transactional注解

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yitian.ssm.dao.UserinfoMapper;
import com.yitian.ssm.entity.Userinfo;
import com.yitian.ssm.entity.UserinfoExample;
import com.yitian.ssm.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService{
	@Autowired
	private UserinfoMapper um;
	@Override
	public List<Userinfo> findByUnameAndUpwd(UserinfoExample example) {
		List<Userinfo> list=(List<Userinfo>) um.selectByExample(example);
		return list;
	}
	//如果有删除有增加,或者其他,必须controller在请求service层1次,不能先调用del() 在调用add(),这种情况不是一个事务,容易出错!
	public int  add(){
		del();
		return 0;
	}
	public int  del(){
		return 0;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值