Springboot @Transactional 事务不回滚

一、异常捕获的原因

  1. 这里Exception异常,他又分为运行时异常RuntimeException和非运行时异常
  2. 可查的异常(checked exceptions):Exception下除了RuntimeException外的异常
  3. 不可查的异常(unchecked exceptions):RuntimeException及其子类和错误(Error)
  4. 异常checked例外也回滚:在整个方法前加上 @Transactional(rollbackFor=Exception.class)
  5. 异常unchecked例外不回滚: @Transactional(notRollbackFor=RunTimeException.class)
  6. 如果异常被try{}catch{}了,事务就不回滚了,如果想让事务回滚必须再往外抛try{}catch{throw Exception}

二、数据库引擎不支持回滚(使用MYSQL就很可能是这个原因)

  1. Mysql数据库有两种引擎,注意要使用支持事务的引擎,比如innodb,如果是MyISAM,事务是不起作用的。
  2. 使用springboot的jpa自动创建库表的时候,默认使用MyISAM引擎,可以检查库表查看引擎。
  3. 修改配置:
    spring:  
      jpa:
        hibernate:
          ddl-auto: update
          naming:
            physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #按字段名字建表
        show-sql: true
        database: mysql
        database-platform: org.hibernate.dialect.MySQL5InnoDBDialect  #使用innodb引擎建表

猜你喜欢

转载自www.cnblogs.com/asker009/p/9368677.html