0


如何开启SpringBoot的事务

如何开启SpringBoot的事务

1. 两种方式

1.1 使用@Transactional注解

通过在方法或类上添加@Transactional注解,SpringBoot会自动为这些方法开启事务。如果方法调用期间发生异常,事务将回滚;如果方法成功执行,事务将提交。

代码演示

importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;@ServicepublicclassGradeService{@TransactionalpublicvoidenterGrades(long studentId,Map<String,Double> grades){// 假设在数据库中有一个grade表,字段包括student_id, course, score等// 遍历grades,依次将学生成绩录入数据库for(Map.Entry<String,Double> entry : grades.entrySet()){String course = entry.getKey();Double score = entry.getValue();// 执行insert语句,将学生studentId在课程course的成绩录入数据库// ...}// 如果任何一门课程的成绩录入失败,事务将会回滚,保持数据的一致性}}

在上述例子中,我们在GradeService类的enterGrades方法上添加了@Transactional注解,这样Spring Boot会为该方法开启事务。

1.2 使用@EnableTransactionManagement注解

在主配置类(通常是应用的入口类)上添加@EnableTransactionManagement注解,启用Spring Boot的事务管理功能。然后在需要开启事务的方法或类上添加@Transactional注解。

代码演示

importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.transaction.annotation.EnableTransactionManagement;@SpringBootApplication@EnableTransactionManagementpublicclassMyApplication{publicstaticvoidmain(String[] args){SpringApplication.run(MyApplication.class, args);}}

在上述例子中,我们在应用的入口类MyApplication上添加了@EnableTransactionManagement注解,这样就启用了SpringBoot的事务管理功能。然后,在需要开启事务的方法或类上添加@Transactional注解,就可以实现事务的管理了。

2. 使用@EnableTransactionManagement注解的情况

@EnableTransactionManagement注解是用于启用Spring的事务管理功能的,它主要用于配置SpringBoot的事务管理器。在某些情况下,SpringBoot可能无法自动识别和配置事务管理器,因此我们需要显式地使用@EnableTransactionManagement来启用事务管理功能,并自定义配置事务管理器。

2.1 自定义事务管理器

如果项目中使用了多个数据源需要使用特定的事务管理器配置,那么@EnableTransactionManagement注解就很有用。我们可以通过这个注解来配置自定义的事务管理器,并与数据源进行关联。

2.2 在非SpringBoot注解扫描的包中使用

在某些情况下,我们可能希望将事务管理配置放在非Spring Boot注解扫描的包中。在这种情况下,Spring Boot默认的事务扫描可能无法生效,我们可以使用@EnableTransactionManagement注解来明确指定事务管理的配置位置。

标签: spring boot java 后端

本文转载自: https://blog.csdn.net/qq_46130027/article/details/131869694
版权归原作者 甜瓜瓜哥 所有, 如有侵权,请联系我们删除。

“如何开启SpringBoot的事务”的评论:

还没有评论