如何开启SpringBoot的事务

悠悠 2023-10-13 22:14 218阅读 0赞

如何开启SpringBoot的事务

    1. 两种方式
    • 1.1 使用@Transactional注解
      • 代码演示
    • 1.2 使用@EnableTransactionManagement注解
      • 代码演示
    1. 使用@EnableTransactionManagement注解的情况
    • 2.1 自定义事务管理器
    • 2.2 在非SpringBoot注解扫描的包中使用

1. 两种方式

1.1 使用@Transactional注解

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

代码演示

  1. import org.springframework.stereotype.Service;
  2. import org.springframework.transaction.annotation.Transactional;
  3. @Service
  4. public class GradeService {
  5. @Transactional
  6. public void enterGrades(long studentId, Map<String, Double> grades) {
  7. // 假设在数据库中有一个grade表,字段包括student_id, course, score等
  8. // 遍历grades,依次将学生成绩录入数据库
  9. for (Map.Entry<String, Double> entry : grades.entrySet()) {
  10. String course = entry.getKey();
  11. Double score = entry.getValue();
  12. // 执行insert语句,将学生studentId在课程course的成绩录入数据库
  13. // ...
  14. }
  15. // 如果任何一门课程的成绩录入失败,事务将会回滚,保持数据的一致性
  16. }
  17. }

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

1.2 使用@EnableTransactionManagement注解

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

代码演示

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.transaction.annotation.EnableTransactionManagement;
  4. @SpringBootApplication
  5. @EnableTransactionManagement
  6. public class MyApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(MyApplication.class, args);
  9. }
  10. }

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

2. 使用@EnableTransactionManagement注解的情况

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

2.1 自定义事务管理器

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

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

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

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot开启事务

    @Transactional 直接在想要启动事务的方法或者类上添加@Transactional注解即可,在类上添加注解,默认类下的所有方法都会使用事务。 在类上添加注解