原因
Mysql中表使用的存储引擎为MyISAM,导致对该表进行事务操作,没有进行正常回滚。
检查@Transactional
- 是否用在public方法上面
- 设置了 Exception.class类,即
@Transactional(rollbackFor = Exception.class)
检查msyql表
检查表存储引擎
zylMBP:~ zhangyalin$ mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1505
Server version: 5.7.19 MySQL Community Server (GPL)
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>use mydatabase;
mysql> SHOW TABLE STATUS WHERE Name = 'link';
结果如下:
当前link表,使用的存储引擎为MyISAM,这个是不支持事务的,要支持事务需要修改为InnoDB。
修改为InnDB
mysql> ALTER TABLE link ENGINE = InnoDB;
Query OK, 2 rows affected (0.04 sec)
Records: 2 Duplicates: 0 Warnings: 0
再次检查
ysql> SHOW TABLE STATUS WHERE Name = 'link';
结果如下:
这样就解决Spring设置事务无效的问题了。还需要设置Spring通过Hibernate创建mysql表默认使用InnoDB的存储引擎。
配置Hibernate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
参考:
springBoot service 事务注解@Transactional不起作用的解决
Spring Boot + JPA MySQL InnoDB 配置
13.7.6.36 SHOW TABLE STATUS Syntax