栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

11.3 SpringBoot 事物支持

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

11.3 SpringBoot 事物支持

Spring Boot 使用事务非常简单,底层依然采用的是Spring本身提供的事务管理

  • 在入口类中使用注解 @EnableTransactionManagement 开启事务支持
  • 在访问数据库的Service方法上添加注解 @Transactional 即可

 案例思路:

        通过SpringBoot +MyBatis实现对数据库学生表的更新操作,在service层的方法中构建异常,查看事务是否生效

实现步骤:

        ① 在StudentController中添加更新学生的方法

@Controller
public class SpringBootController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/springBoot/update")
    public @ResponseBody Object update() {
        Student student = new Student();
        student.setId(1);
        student.setName("Mark");
        student.setAge(100);

        int updateCount = studentService.update(student);

        return updateCount;
    }

}

②​​​​​​​在StudentService接口中添加更新学生方法

ublic interface StudentService {

    
    int update(Student student);
}

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

Override
@Transactional //添加此注解说明该方法添加的事务管理
public int update(Student student) {

    int updateCount = studentMapper.updateByPrimaryKeySelective(student);

    System.out.println("更新结果:" + updateCount);

    //在此构造一个除数为0的异常,测试事务是否起作用
    int a = 10/0;

    return updateCount;
}

④​​​​​​​在Application类上加@EnableTransactionManagement开启事务支持

@EnableTransactionManagement可选,但是@Service必须添加事务才生效

@SpringBootApplication
@EnableTransactionManagement //SpringBoot开启事务的支持
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

⑤启动Application,通过浏览器访问进行测试

测试结果:浏览器会报 500;控制台会报 erro 错误;数据库信息未更改,说明事物起作用了。

​​​​​​​注释掉StudentServiceImpl上的@Transactional测试,数据库数据被更新,说明事物未起效(即未启动)。

异常:提供 程序出现例外情况,通过妥善处理,让程序能够执行下去的 一种机制
  运行时异常:非受检查异常  由于程序人员考虑不周密,出现的例外情况
  编译时异常:受检查异常    提醒检查程序

事物起作用就是在监控编译时异常,要想运行时异常事物也起作用,需要在注解中设置属性。在业务逻辑层添加属性 rollerbackFor(事物回滚)

 @Override
    @Transactional(rollbackFor = FileNotFoundException.class,propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    public int update(Student student) throws FileNotFoundException {
        int num = studentMapper.updateByPrimaryKeySelective(student);
       // int j=100/0;
        new FileInputStream("");

        return num;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572363.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号