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)
(本文出自oschina博主文章:https://my.oschina.net/happyBKs/blog/1624482)
6、非springboot项目,需要检查spring配置文件xml中:
(1)扫描包范围是否配置好,否则不会在启动时spring容器中创建和加载对应的bean对象。
<context:component-scan base-package="com.happybks" ></context:component-scan>
(2)事务是否已经配置成开启
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
7、springboot项目有两个可选配置,默认已经支持事务了,可以写也可以不写。
(1)springboot启动类,即程序入口类,需要注解@EnableTransactionManagement
1package com.happybks.pets; 2 3import org.springframework.boot.SpringApplication; 4import org.springframework.boot.autoconfigure.SpringBootApplication; 5import org.springframework.transaction.annotation.EnableTransactionManagement; 6 7@EnableTransactionManagement 8@SpringBootApplication 9public class PetsApplication { 10 11 public static void main(String[] args) { 12 SpringApplication.run(PetsApplication.class, args); 13 } 14}
(2)springboot配置文件application.yml中,可以配置上失败回滚:
1spring: 2 profiles: 3 active: prod 4 datasource: 5 driver-class-name: com.mysql.jdbc.Driver 6 url: jdbc:mysql://127.0.0.1:3306/spbdb 7 username: root 8 password: 9 jpa: 10 hibernate: 11 ddl-auto: 12 show-sql: true 13 transaction: 14 rollback-on-commit-failure: true
下面简单看个例子:
还是在上一篇博客文章的示例的基础上,我们追加一个Service类,名叫涨价服务类:
1package com.happybks.pets; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.stereotype.Service; 5import org.springframework.transaction.annotation.Transactional; 6 7import java.util.List; 8 9@Service 10public class PriceService { 11 12 13 @Autowired 14 PetRepository petRepository; 15 16 @Transactional(rollbackFor=Exception.class) 17 public void putUpPrice() { 18 19 List<PetEntity> allPets = petRepository.findAll(); 20 for (PetEntity pet : allPets) { 21 pet.setPrice(pet.getPrice() * 1.1); 22 System.out.println(pet.getBreedType() + "打算涨到" + pet.getPrice()); 23 if (pet.getBreedType().contains("猫")) { 24 for (int i = 0; i < 255; i++) { 25 pet.setBreedType(pet.getBreedType() + "喵喵说了,不许涨价"); 26 } 27 } 28 petRepository.save(pet); 29 } 30 31 } 32}
要做的事情就是把宠物数据表中所有的宠物价格涨10%。这里我有意让有关猫的宠物修改它们的名称字段,让名称字段超过数据表中定义的255的长度限制。这种异常肯定属于运行阶段的数据库操作异常,所以肯定能触发事务回滚。

这里我的表里,布偶猫正好排在狗的后面,如果事务回滚成功,那么狗的价钱不会变。
于是我们请求:发现最终结果狗的价钱也没变。

控制台输出:

数据表中数据不变,说明事务回滚了。
