Spring Boot事物Transactional不起作用排除

(本文出自oschina博主文章:https://my.oschina.net/happyBKs/blog/1624482)
spring对事务的管理,之前的博客文章中也介绍过,不再详细累述。
本文想说的是,当@Transactional不起作用如何排查问题。

可以按照以下几个步骤逐一确认:

  1. 首先要看数据库本身对应的库、表所设置的引擎是什么。MyIsam不支持事务,如果需要,则必须改为InnnoDB。

  2. @Transactional所注解的方法是否为public

  3. @Transactional所注解的方法所在的类,是否已经被注解@Service或@Component等。

  4. 需要调用该方法,且需要支持事务特性的调用方是在在 @Transactional所在的类的外面。注意:类内部的其他方法调用这个注解了@Transactional的方法,事务是不会起作用的。

  5. 注解为事务范围的方法中,事务的回滚仅仅对于unchecked的异常有效。对于checked异常无效。也就是说事务回滚仅仅发生在出现RuntimeException或Error的时候。
    如果希望一般的异常也能触发事务回滚,需要在注解了@Transactional的方法上,将 @Transactional回滚参数设为:

    @Transactional(rollbackFor=Exception.class)
    
  6. 非springboot项目,需要检查spring配置文件xml中:

    • 扫描包范围是否配置好,否则不会在启动时spring容器中创建和加载对应的bean对象。
    <context:component-scan base-package="com.happybks" ></context:component-scan>
    
    • 事务是否已经配置成开启
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    
  7. springboot项目有两个可选配置,默认已经支持事务了,可以写也可以不写。

    • springboot启动类,即程序入口类,需要注解@EnableTransactionManagement
    package com.happybks.pets;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    @EnableTransactionManagement
    @SpringBootApplication
    public class PetsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(PetsApplication.class, args);
        }
    }
    
    • springboot配置文件application.yml中,可以配置上失败回滚:
    spring:
       profiles:
          active: prod
       datasource:
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/spbdb
          username: root
          password:
      jpa:
          hibernate:
          ddl-auto:
          show-sql: true
      transaction:
          rollback-on-commit-failure: true
    
发布了36 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Cmainlove/article/details/84033489