Spring Boot使用事务

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

依赖的Jar包pom.xml

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

<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

@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("tenmao:" + person.getName());
        companyMapper.insertOne(company);
        personMapper.insertOne(person);
    }
}

注解属性

  • rollbackFor:触发回滚的异常,默认是RuntimeExceptionError
  • isolation: 事务的隔离级别,默认是Isolation.DEFAULT也就是数据库自身的默认隔离级别,比如MySQL是ISOLATION_REPEATABLE_READ可重复读

这样就可以了,不需要其他配置。

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