springboot注解以及手动使用事务

 


一、注解方式

springBoot项目要用事务,使用注解方式时只需要在启动类加上@EnableTransactionManagement。

并在想使用事务的方法中加上@Transactional注解即可。

复制代码
@SpringBootApplication
//①在启动类中加上注解
@EnableTransactionManagement
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
 
//②在对应的方法中加注解
@Transactional(rollbackFor = Exception.class)
public void registerUser(User user) throws Exception {
   ...
   userMapper.updateUser(user);
   ...

}
复制代码

附:@Transactional参数说明: 

事务传播行为

事务传播行为(propagation behavior)指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。
例如:methodA事务方法调用methodB事务方法时,methodB是继续在调用者methodA的事务中运行呢,还是为自己开启一个新事务运行,这就是由methodB的事务传播行为决定的。
Spring定义了七种传播行为:(默认为Propagation.REQUIRED)

 二、方法内部手动控制事务

2.1、注入事务相关的bean

@Autowired
private PlatformTransactionManager platformTransactionManager;

@Autowired
private TransactionDefinition transactionDefinition;

2.2、结合try-catch使用事务

TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
try {
    dosomething....
    platformTransactionManager.commit(transactionStatus);
} catch (Exception e) {
    platformTransactionManager.rollback(transactionStatus);
}

 

posted @   Arbitrary233  阅读(2518)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示