最近发现事务不会回滚,查了原因总结一下原因:
1、@Transactional 没注解在public方法上
2、抛出的异常不是RuntimeException类异常,而@Transactional上没有注明rollbackFor哪一类异常。
解决方法可以是@Transactional( rollbackFor = Exception.class)
3、数据库存储引擎不支持回滚
以mysql为例,数据库引擎是MyISAM不回滚。把引擎改为InnoDB会回滚。
-- 查看库的存储引擎
show engines;
-- 查看表的存储引擎
-- show create table tablename;
-- 修改表的存储引擎
-- alter table tablename engine=InnoDB;
3.1、附批量修改表的存储引擎方法
-- 查看库里所有表
select * from information_schema.tables where table_schema='db_xiaoxiao_dev' and table_type='base table';
-- 批量行到修改表的存储引擎脚本
select CONCAT('alter table ',table_name,' engine=InnoDB;') from information_schema.tables where table_schema='db_xiaoxiao_dev' and table_type='base table' and `ENGINE`='MyISAM';
3.2、通常spring boot都会利用jpa直接创建表,如果要使创建的表引擎是InnoDB,则在配置文件中要加上
jpa: database-platform: org.hibernate.dialect.MySQL5InnoDBDialect