事务处理需要新增命名空间:
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>