Spring Boot事务使用

Spring Boot实现事务特别特别简单,没有多余操作,一个注解@Transactional搞定

依赖的Jar包pom.xml

Spring Boot中实现事务没有额外的Jar包,还是基本的数据库访问包,比如Mybatis

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>

注解事务@Transactional

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class PersonService {
@Resource
private PersonMapper personMapper;

@Resource
private CompanyMapper companyMapper;

@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public void saveOne(Person person) {
Company company = new Company();
company.setName(person.getName());
companyMapper.insertOne(company);
personMapper.insertOne(person);
}
}

ps:网络上还说要在@SpringBootApplication上添加注解@EnableTransactionManagement,已经不需要配置

默认回滚策略

默认遇到throw new RuntimeException("…");会回滚
需要捕获的throw new Exception("…");不会回滚

指定回滚策略

  • 指定回滚
1
2
3
4
5
@Transactional(rollbackFor=Exception.class)
public void methodName() {
// 不会回滚
throw new Exception("...");
}
  • 指定不回滚
1
2
3
4
5
@Transactional(noRollbackFor=Exception.class)
public ItemDaoImpl getItemDaoImpl() {
// 会回滚
throw new RuntimeException("注释");
}

注解属性

  • @Transactional(rollbackFor = Exception.class):触发回滚的异常,默认是RuntimeExceptionError
  • @Transactional(propagation = Propagation.REQUIRED):如果有事务,那么加入事务,没有的话新建一个(不写的情况下)
  • @Transactional(propagation = Propagation.NOT_SUPPORTED):容器不为这个方法开启事务
  • @Transactional(propagation = Propagation.REQUIRED, readOnly=true)readOnly=true只读,不能更新,删除
  • @Transactional(propagation = Propagation.REQUIRED, timeout=30):设置超时时间
  • @Transactional(propagation = Propagation.REQUIRED, isolation=Isolation.DEFAULT): 事务的隔离级别,即数据库隔离级别,默认是Isolation.DEFAULT也就是数据库自身的默认隔离级别,比如MySQL是ISOLATION_REPEATABLE_READ可重复读

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :