Spring Boot事务支持
文章目录
Spring Boot 事务支持
Spring Boot 使用事务非常简单,底层依然采用的是 Spring 本身提供的事务管理
➢ 在入口类中使用注解 @EnableTransactionManagement 开启事务支持
➢ 在访问数据库的 Service 方法上添加注解 @Transactional 即可
1、案例思路
通过 SpringBoot +MyBatis 实现对数据库学生表的更新操作,在 service 层的方法中构建
异常,查看事务是否生效
项目名称:012-springboot-web-mybatis-transacation
该项目是在 011 的基础上添加新增方法,在新增方法中进行案例的演示
2、实现步骤
(9) 在 StudentController 中添加更新学生的方法

(10) 在 StudentService 接口中添加更新学生方法


(11) 在 StudentServiceImpl 接口实现类中对更新学生方法进行实现,并构建一个异常,同时在该方法上加@Transactional 注解

(12) 在 Application类上加@EnableTransactionManagement 开启事务支持
@EnableTransactionManagement 可选,但是业务方法上必须添加@Transactional 事务才生效

(13) 启动 Application,通过浏览器访问进行测试


通过以上结果,说明事务起作用了
(14) 注释掉 StudentServiceImpl 上的@Transactional 测试数据库的数据被更新


评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论