SpringBoot笔记5 事务特别篇——当@Transactional不起作用如何排查问题

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

package com.happybks.pets;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
public class PetsApplication {

	public static void main(String[] args) {
		SpringApplication.run(PetsApplication.class, args);
	}
}

(2)springboot配置文件application.yml中,可以配置上失败回滚:

spring:
  profiles:
    active: prod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/spbdb
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto:
    show-sql: true
  transaction:
    rollback-on-commit-failure: true

下面简单看个例子:

还是在上一篇博客文章的示例的基础上,我们追加一个Service类,名叫涨价服务类:
 

package com.happybks.pets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PriceService {


    @Autowired
    PetRepository petRepository;

    @Transactional(rollbackFor=Exception.class)
    public void putUpPrice() {

        List<PetEntity> allPets = petRepository.findAll();
        for (PetEntity pet : allPets) {
            pet.setPrice(pet.getPrice() * 1.1);
            System.out.println(pet.getBreedType() + "打算涨到" + pet.getPrice());
            if (pet.getBreedType().contains("猫")) {
                for (int i = 0; i < 255; i++) {
                    pet.setBreedType(pet.getBreedType() + "喵喵说了,不许涨价");
                }
            }
            petRepository.save(pet);
        }

    }
}

要做的事情就是把宠物数据表中所有的宠物价格涨10%。这里我有意让有关猫的宠物修改它们的名称字段,让名称字段超过数据表中定义的255的长度限制。这种异常肯定属于运行阶段的数据库操作异常,所以肯定能触发事务回滚。

这里我的表里,布偶猫正好排在狗的后面,如果事务回滚成功,那么狗的价钱不会变。

于是我们请求:发现最终结果狗的价钱也没变。

控制台输出:

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

猜你喜欢

转载自my.oschina.net/happyBKs/blog/1624482
今日推荐