最近發現事務不會回滾,查了原因總結一下原因:
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