SpringBoot 事务的应用

来源:互联网 发布:ubuntu pyqt 安装 编辑:程序博客网 时间:2024/05/23 14:52

SpringBoot 事务的应用

今天学习了下关于SpringBoot中事务的应用,记录一下。

事务的概念呀四个特性呀这里就不说了呀。简单来说:操作要么全做,要么全不做。还是以银行转账为例,A转账到B:必须是A账户扣钱成功且B账户到账成功,而不允许出现A账户扣钱成功呀B账户没有收到钱等等,这都是不允许出现的,如果发生在你身上,必须要去投诉,是吧。

简单的应用

同样,本文在上篇博文中的Demo基础上做为例子来进行说明。现在假设有这样两个操作:在dbstudent数据库中的student表中既存储A学生的信息也存储B学生的信息,如果有其中一个没有存储成功,则都不进行存储。

关于spring-data.jpa和mysql的相关依赖和配置可以见上篇博文。

具体操作如下:

1、首先建立一个StudentService类

该类中有一个方法,该方法用来模拟存储两个学生,且该方法使用了@Tranctional来进行注解,这样该方法中的所用操作就构成了一个事务,是不是很简单。

    @Component    public class StudentService {        @Autowired        private StudentRepository studentRepository;        @Transactional        public void addTwoStudentInfo(){            Student studentA = new Student();            studentA.setAge(18);            studentA.setName("xiaoming");            studentRepository.save(studentA);            Student studentB = new Student();            studentB.setAge(19);            studentB.setName("xiaohuaheihei");            studentRepository.save(studentB);        }    }

2、然后在我们的控制器类StudentController中添加如下代码即可。

    @RestController    @RequestMapping("/student")    public class StudentController {        @Autowired        private  StudentService studentService;        @PostMapping(value="/addTwo")        public void addTwo(){            studentService.addTwoStudentInfo();        }    }

如何来测试我们这个是否正确呢,即是否真的使用@Transactional注解之后就可以用来保证操作要么全做要么全不做呢?

可以这样来测试。

1、借助于sequel pro工具将dbstudent数据库中student表的name属性的长度限定为:8.

如下图所示

这样设定之后,studentA=xiaoming的长度符合要求,studentB的name=xiaohuaheihei长度明显大于此长度,这样我们就制造了一个事务失败的例子。

运行该Demo,即可在数据库中观察结果:确实都没有存储成功,而且在控制台也报了相关的错误,错误如下:

以上就时SpringBoot项目中事务的一个简单的应用。

下面来介绍下事务管理器的相关知识。以下参考与该博客:
http://blog.csdn.net/catoop/article/details/50595702

关于事务管理器,不管是JPA还是JDBC等都实现自接口 PlatformTransactionManager 。

如果你添加的是 spring-boot-starter-jdbc 依赖,框架会默认注入 DataSourceTransactionManager 实例。

如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。

可以通过如下的代码来观察自动注入的是PlatformTransactionManager接口的哪个实现类。

    @SpringBootApplication    public class TransactiondemoApplication {        @Bean        public Object testBean(PlatformTransactionManager platformTransactionManager){            System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());            return new Object();        }        public static void main(String[] args) {            SpringApplication.run(TransactiondemoApplication.class, args);        }    }

运行程序,在控制台会打印出如下信息:

>>>>>>>>>>org.springframework.orm.jpa.JpaTransactionManager。

与我们pom.xml文件中添加的依赖为:spring-boot-starter-data-jpa相符合。

如果我们在pom.xml不添加jpa或jdbc的相关依赖,则,在运行程序时,输入的信息为:

>>>>>>>>>>org.springframework.boot.autoconfigure.transaction.TransactionProperties

如果有多个事务管理器,该如何指定呢,该博文http://blog.csdn.net/catoop/article/details/50595702有一定的介绍。

对于不同数据源的事务管理配置可以见该博文:http://blog.didispace.com/springbootmultidatasource/

小结

本篇博文就学习了下关于事务的简单应用。

0 0
原创粉丝点击