## Spring事务
-
事务作用:在数据层保障一系列的数据库操作同成功同失败。
-
Spring事务作用:在数据层或业务层保障一系列的数据库操作同成功同失败。
-
代码实现:
-
在业务层接口(降低耦合)上添加@Transactional注解:开启事务
-
public interface AccountService { /** * 转账操作 * @param out 传出方 * @param in 转入方 * @param money 金额 */ @Transactional//当前接口方法开启事务,也可以添加到类/接口上 public void transfer(String out,String in ,Double money); }
-
-
在jdbc配置类中配置事务管理器
-
public class JdbcConfig { //配置事务管理器,mybatis使用的是jdbc事务管理器 @Bean public PlatformTransactionManager transactionManager(DataSource dataSource){//注入数据源对象 DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource); return transactionManager; } }
-
-
在spring配置类上添加@EnableTransactionManagement注解:开启注解式事务驱动
-
@Configuration @ComponentScan("com.itheima") @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class,MybatisConfig.class}) //开启注解式事务驱动 @EnableTransactionManagement public class SpringConfig { }
-
-
Spring事务角色
- 事务角色
- 事务管理员:发起事务方,在Spring中通常指代业务层开启事物的方法。
- 事务协调员:加入事务方,在Spring中通常指代数据层方法,也可以是业务层方法。
Spring事务属性
-
@Transactional():默认回滚Error错误和RuntionException运行时异常,不回滚编译时异常。
-
回滚编译时异常:
-
@Transactional(rollbackFor = IOException.class)//填写具体的编译时异常
-
-
案例:转账业务追加日志,无论转账操作是否成功,均进行转账操作的日志留痕。
-
转账业务层实现类
-
@Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Autowired private LogService logService; public void transfer(String out,String in ,Double money) throws IOException { try { accountDao.outMoney(out,money); //if (true) throw new IOException(); int i = 1 / 0; accountDao.inMoney(in,money); } finally { //finally无论成功与否都要记录日志 logService.log(out,in,money); } } }
-
-
转账业务实现类设置事务传播行为,将该事务从事务管理员中隔离出去。
-
public interface LogService { //propagation设置事务属性:设置事务传播行为 //将该事务,从事务管理员独立出去,形成新的事物。 @Transactional(propagation = Propagation.REQUIRES_NEW) void log(String out, String in, Double money); }
-
-
事务属性
- 事务传播行为属性