Spring 事务控制
- JavaEE体系分层开发,事务处理位于业务层,Spring提供了业务层事务处理方案。
- spring提供了事务控制接口
- spring事务控制基于AOP,可以通过配置实现
<!-- 事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
事务支持的方法
//事务名称
String getName()
//事务隔离等级
int getIsolationLevel()
//事务传播行为,什么情况下可以有事务
int getPropagationBehavior()
//事务超时时间
int getTimeout()
//事务是否只读,查询即只读
boolean isReadOnly()
基于XML的事务控制
- 配置事务管理器
- 配置事务通知:导入事务的约束
- 配置事务属性
- 配置AOP中的切入点表达式
- 建立事务通知和切入点对应关系
<!--声明式事务管理-->
<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="*" propagation="REQUIRED" read-only="false"/>
<!--部分匹配优先级更高-->
<tx:method name="select*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--AOP增强-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pc" expression="execution(* demo.service.impl.*.*(..))"/>
<aop:pointcut id="pc2" expression="execution(* *..*.*(..))"/>
<!--建立切入点表达式和事务通知的对应关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
</aop:config>
<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<-tx:method/>中的属性
isolation: 事务隔离级别,默认DEFAULT,数据库默认隔离级别
propagation:用于指定传播行为,默REQUIRED,表示一定会有事务,增删改选择。查询方法可以选择SUPPORTS
read-only:用于指定业务是否只读。只有查询方法设置为true,默认值false(读写)
timeout:用于指定业务超市时间,默认值-1(永不超时),如果指定数值,以秒为单位
no-rollback-for:指定异常不回滚,其他异常回滚,没有默认值,表示都回滚
rollback-for:指定异常,产生异常时,事务回滚,其他异常不回滚,没有默认值,表示任何异常都回滚
测试转账方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:SpringConfig.xml")
public class TestSSM {
@Autowired
private IEmployeeService employeeService;
@Test
public void testTransfer(){
employeeService.transferSalary("c","d", (float) 500.0);
}
}
转账方法
@Override
public void transferSalary(String sourceName, String targetName, Float money) {
//1 查询账户
Employee ee1 = employeeDao.selectByName(sourceName);
Employee ee2 = employeeDao.selectByName(targetName);
//2 金额
ee1.setSalary(ee1.getSalary() - money);
ee2.setSalary(ee2.getSalary() + money);
//3 存入账户
employeeDao.updateEmployee(ee1);
//除零错误
int n = 1/0;
employeeDao.updateEmployee(ee2);
}
基于注解的事务配置
- 配置事务管理器
- 开启spring对注解事务的支持
- 需要事务的地方使用
@Transcational
<!--开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"/>
增加@Transactional
注解
@Override
@Transactional(rollbackFor = {RuntimeException.class,Exception.class})
public void transferSalary(String sourceName, String targetName, Float money) {
//1 查询账户
Employee ee1 = employeeDao.selectByName(sourceName);
Employee ee2 = employeeDao.selectByName(targetName);
//2 金额
ee1.setSalary(ee1.getSalary() - money);
ee2.setSalary(ee2.getSalary() + money);
//3 存入账户
employeeDao.updateEmployee(ee1);
int n = 1/0;
employeeDao.updateEmployee(ee2);
}