Spring事务管理分为编程式事务和声明式事务,但是编程式事务过于复杂并且具有高度耦合性,违背了Spring框架的设计初衷,因此这里只讲解声明式事务。

声明式事务是基于AOP实现。

使用Spring事务代替自己手动openSession的好处是,出现异常会自动回滚并且实现了隔离机制

注册声明式事务

先在配置类添加@EnableTransactionManagement注解即可,这样就可以开启Spring的事务支持,然后创建一个事务管理器并添加Bean:

@Configuration
@ComponentScan("org.example")
@MapperScan("org.example.mapper")
@EnableTransactionManagement
public class MainConfiguration {
 
    @Bean
    public TransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
  	...

之后就使用 @Transactional 来创建事务。

接着定义对应的Mapper:

@Mapper
public interface TestMapper {
    ...
 
    @Insert("insert into student(name, sex) values('测试', '男')")
    void insertStudent();
}

然后编写service层来实现事务 :

public interface TestService {
    void test();
}
@Component
public class TestServiceImpl implements TestService{
 
    @Resource
    TestMapper mapper;
 
    @Transactional   //此注解表示事务,之后执行的所有方法都会在同一个事务中执行
    public void test() {
        mapper.insertStudent();
        if(true) throw new RuntimeException("我是测试异常!");
        mapper.insertStudent();
    }
}

这里插入第一个之后会出现异常来终止事务,结束运行后发现第一个插入也被回滚。