Spring学习笔记-Spring事务

## 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);
        }
        
  • 事务属性

在这里插入图片描述

  • 事务传播行为属性

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值