Spring事务介绍
Spring事务作用:在数据层或业务层保障一系列的数据库操作同成功同失败。
Spring为了管理事务,提供了一个平台事务管理器PlatformTransactionManager
PlatformTransactionManager
只是一个接口,Spring还为其提供了一个具体的实现类DataSourceTransactionManager
。
从名称上可以看出,我们只需要给他一个DataSource对象,他就可以帮你去在业务层管理事务。其内部采用的是JDBC的事务。后期Spring整合Mybatis就是采用DataSourceTransactionManager事务管理器。
使用Spring进行事务管理的关键步骤如下:
- 在需要被事务管理的方法上添加注解
- 在JdbcConfig类中配置事务管理器
- 在SpringConfig中开启事务注解
接下来通过一个转账业务的案例,来学习spring是如何管理事务的。
需求:A账户减钱,B账户加钱
环境搭建
- 准备数据库表
create database spring_db character set utf8;
use spring_db;
create table tbl_account(
id int primary key auto_increment,
name varchar(35),
money double
);
insert into tbl_account(name,money)
values('fyc',200),
('ghh',1000);
- 创建项目导入jar包
<dependencies>
<!--Spring-context为Spring开发的基本包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Spring操作jdbc的jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--mybatis提供的整合spring的jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--单元测试jar包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--Spring整合测试的jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
</dependencies>
- 根据表创建模型
package com.itheima.domain;
import java.io.Serializable;
//与表对应的模型类
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
- 创建Dao接口
package com.itheima.dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface AccountDao {
@Update("update tbl_account set money = money + #{money} where name = #{name}")
void inMoney(@Param("name") String name, @Param("money") Double money);
@Update("update tbl_account set money = money -#{money} where name = #{name}")
void outMoney(@Param("name") String name,@Param("money") Double money);
}
- 创建Service接口和实现类
import java.io.IOException;
public interface AccountService {
public void transfer(String out,String in,Double money) throws IOException;
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void transfer(String out, String in, Double money) throws IOException {
accountDao.inMoney(in,money);
accountDao.outMoney(out,money);
}
}
- 添加jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
- 创建JdbcConfig配置类
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
- 创建MyBatisConfig配置类
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.itheima.domain");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
}
- 创建SpringConfig配置类
@Configuration
@EnableTransactionManagement
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
10.编写测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer() throws IOException {
accountService.transfer("fyc","ghh",100D);
}
}
以上操作便完成了环境搭建,接下来开始Spring事务管理的操作。
- 在需要被事务管理的类上添加注解,
@Transactional(rollbackFor = {IOException.class})
public void transfer(String out, String in, Double money) throws IOException {
try {
accountDao.inMoney(in,money);
// if (true) throw new IOException();
accountDao.outMoney(out,money);
} finally {
logService.log(out,in,money);
}
}
- 在JdbcConfig配置类中配置事务管理器
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
- 在SpringConfig配置类中开启事务注释
@EnableTransactionManagement
至此便完成了使用Spring事务管理转账业务。接下来我们修改业务层层代码,让他抛出除零异常,之后在测试类中进行测试查看是否会回滚。结果表明确实是会回滚。
需要注意的是:Spring的事务只会对Error异常和RuntimeException异常以及其子类异常进行事务回滚。
Spring事务角色
在上面的例子中,Dao接口中的两个方法原本是属于不同的事务,但在通过Spring事务管理的方式下变成了同一事务。
开启Spring事务管理后:
- transfer方法上添加了@Transactional注解,在该方法上就会有一个事务T
- AccountDao的outMoney方法的事务T1就会加入到transfer的事务T中
- AccountDao中的inMoney方法的事务T2也会加入到transfer的事务T中
- 这样就可以保证他们在同一个事务下,当业务层出现异常,整个事务就回滚,保证数据的准确性。
在这里有两个概念:事务管理员和事务协调员
事务管理员:发起事务方,在Spring中通常指代业务层开启事务的方法。
事务协调员:加入事务方,在Spring中通常代指数据层方法,也可以是业务层方法。
Spring事务属性
事务配置
在@Transactional注解的可以设置一些参数。
属性 | 作用 | 示例 |
---|---|---|
readOnly | 设置是否为只读事务 | readOnly = true 只读事务 |
timeOut | 设置事务超时时间 | timeout = -1(永不超时) |
rollbackFor | 设置事务回滚异常(class) | @Transactional(rollbackFor ={ NullPointException.class}) |
… | … | … |
propagation | 设置事务传播行为 | @Transactional(propagation = Propagation.REQUIRES_NEW) |
- readOnly:true只读事务,false读写事务,增删改为false,查询为true。
- timeout:设置超时时间单位秒,在多长时间之内事务没有提交成功就自动回滚,-1表示不设置超时时间。
- rollbackFor:当出现指定异常进行事务回滚
- propagation:事务传播行为,事务协调员对事务管理员所携带事务的处理态度。
转账业务追加日志
需求:无论转账操作是否成功,均进行转账操作的日志留痕。
具体实现:
- 创建日志表
create table tbl_log(
id int primary key auto_increment,
info varchar(255),
createDate DATETIME
)
- 添加LogDao接口
public interface LogDao {
@Insert("insert into tbl_log (info,createDate) values (#{info},now())")
void log(String log);
}
- 添加LogService接口及实现类
public interface LogService {
void log(String out,String in,Double money);
}
@Service
public class LogServiceImpl implements LogService {
@Autowired
private LogDao logDao;
public void log(String out, String in, Double money) {
logDao.log("转账操作由"+out+"到"+in+",金额:"+money);
}
}
- 在转账的业务中添加日志(使用try-finally结构 确保添加日志方法一定被执行)
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private LogService logService;
@Transactional(rollbackFor = {IOException.class})
public void transfer(String out, String in, Double money) throws IOException {
try {
accountDao.inMoney(in,money);
// if (true) throw new IOException();
accountDao.outMoney(out,money);
} finally {
logService.log(out,in,money);
}
}
}
- 运行程序
当我们在AccountServiceImpl中添加异常后,我们发现事务进行回滚,所以tbl_account中的记录不会发生变化,但tbl_log中也没有添加记录,因为他们都处在同一个事务下。显然这不是我们想要的结果,此时就需要用到事务传播行为。
让LogServiceImpl作为事务协调者在事务管理者提供事务的前提下提供新的事务。 - 修改LogService改变事务的传播行为
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void log(String out, String in, Double money) {
logDao.log("转账操作由"+out+"到"+in+",金额:"+money);
}
通过为LogServiceImpl中的log方法添加 @Transactional(propagation = Propagation.REQUIRES_NEW)
注解的方式,成功将转钱操作和记录日志操作变为两个不同的事务,从而保证日志一定会被记录。
事务传播行为
事务传播行为是指事务协调员对事务管理员所携带事务的处理态度。前面的转账业务追加日志便用到了事务传播行为。
事务传播行为的可选值
对Spring事务的学习总结
Spring事务:保证数据层或是业务层一系列数据库操作同时成功或者失败
操作步骤:总共有3步,具体如下:
- 为需要被事务管理的方法添加
@Transactional
注解 - 在JdbcConfig配置类中添加事务管理器
- 在SpringConfig配置类中开启注解事务
Spring事务角色:事务管理者和事务协调者
事务管理者:通常是指业务层开启事务的方法
事务协调这:通常是指数据层方法,也可以使业务层方法
事务传播行为:事务协调员对事务管理员所携带事务的处理态度