Spring事务传播机制

开发中有多个事务方法嵌套调用时,就涉及到了 Spring 的事务传播机制。

下面梳理一下 7 种传播机制的含义,做一些测试以加深理解,也方便开发中灵活使用。

1. Spring事务传播类型枚举Propagation

  • REQUIRED: 没有事务就开启,有事务就加入,不指定的话默认为该类型
  • SUPPORTS: 有事务就加入,没有就无事务运行
  • MANDATORY: 加入当前事务,如果不存在则抛出异常
  • REQUIRES_NEW: 没有就开启,有了挂起原来的,开启新的
  • NOT_SUPPORTED: 有了挂起,没有就无事务运行
  • NEVER: 以非事务方式执行,如果存在事务则抛出异常
  • NESTED: 如果当前事务存在,则在嵌套事务中执行,否则行为类似于REQUIRED

大多数情况下,用默认的 REQUIRED 就足够了,其它的用的较少。

2. 传播机制测试

2.1 测试准备

Spring Boot,JPA,Lombok,MySQL

建表:

CREATE TABLE `region`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

建实体:

package com.jiangxb.transactional;

import lombok.Builder;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 地区实体
 *
 * @author: jiangxiangbo
 * @date: 2021/6/16
 */
@Entity
@Table(name = "region")
@Data
@Builder
public class Region {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(name = "name")
    private String name;
    
}

repository:

package com.jiangxb.transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * region repository
 *
 * @author: jiangxiangbo
 * @date: 2021/6/16
 */
@Repository
public interface RegionRepository extends JpaRepository {
}

service:

package com.jiangxb.transactional;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地区service
 *
 * @author: jiangxiangbo
 * @date: 2021/6/16
 */
@Service
public class RegionService {
    
    @Autowired
    private RegionRepository regionRepository;
    
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insertRegion() {
        regionRepository.save(Region.builder().name("A").build());
        
        // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
        RegionService regionService = (RegionService)AopContext.currentProxy();
        regionService.insertRegionB();
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insertRegionB() {
        regionRepository.save(Region.builder().name("B").build());
//        throw new RuntimeException();
    }
}

controller:

package com.jiangxb.transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 事务测试
 *
 * @author: jiangxiangbo
 * @date: 2021/6/16
 */
@RestController
public class TransactionalController {
    @Autowired
    private RegionService regionService;
    
    @GetMapping("/propagation")
    public void propagation() {
        regionService.insertRegion();
    }
}

application:

package com.jiangxb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
// 需要进行该设置,否则 AopContext.currentProxy() 获取代理对象报错
// Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class DemoStudyApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoStudyApplication.class, args);
    }
}

2.2 REQUIRED

REQUIRED: 没有事务就开启,有事务就加入,不指定的话默认为该类型。

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:AB 插入失败

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A插入成功B 插入失败
**

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    try {
        regionService.insertRegionB();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A、B插入失败。
注意:REQUIRED类型下,这两个方法其实是在同一个事务内,insertRegionB()方法回滚,导致同个事务中的insertRegion()也回滚,即使在其中catch了异常也不行。 可与下面 NESTED级别进行对比。NESTED类型下,A成功B失败,该类型下 insertRegionB() 是一个子事务,子事务回滚不会导致父事务回滚。

2.3 SUPPORTS

SUPPORTS: 有事务就加入,没有就无事务运行

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:AB 插入失败

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:AB 插入成功

2.4 MANDATORY

MANDATORY: 加入当前事务,如果不存在则抛出异常

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.MANDATORY, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:AB 插入失败

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.MANDATORY, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A 插入成功,调用 insertRegionB() 时抛出异常
org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'

2.5 REQUIRES_NEW

REQUIRES_NEW: 没有就开启,有了挂起原来的,开启新的

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
    
    throw new RuntimeException();
}

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
}

结果:A 插入失败,B插入成功。因为 insertRegionB() 新起了一个事务,与 insertRegion() 不在同一个事务中,所以不会回滚。

2.6 NOT_SUPPORTED

NOT_SUPPORTED: 有了挂起,没有就无事务运行
也就是不论是否有事务,方法都会以非事务的方式运行。

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A 插入失败,B插入成功。

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A、B插入成功。

2.7 NEVER

NEVER: 以非事务方式执行,如果存在事务则抛出异常

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
}

@Transactional(propagation = Propagation.NEVER, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A 插入失败,调用 insertRegionB() 时抛出异常
org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'

2.8 NESTED

NESTED: 如果当前事务存在,则在嵌套事务中执行,否则行为类似于REQUIRED

主要测试下当前存在事务的情况:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    regionService.insertRegionB();
    
    throw new RuntimeException();
}

@Transactional(propagation = Propagation.NESTED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
}

insertRegionB() 是 insertRegion() 的子事务,父事务回滚,子事务也会回滚。**
结果:A 、B插入失败
注意:这与 REQUIRES_NEW 不同,REQUIRES_NEW 的话 B 会插入成功

public void insertRegion() {
    regionRepository.save(Region.builder().name("A").build());

    // 调用同个类中的事务方法需要使用代理对象调用,否则事务无效
    RegionService regionService = (RegionService)AopContext.currentProxy();
    try {
        regionService.insertRegionB();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Transactional(propagation = Propagation.NESTED, rollbackFor = Exception.class)
public void insertRegionB() {
    regionRepository.save(Region.builder().name("B").build());
    throw new RuntimeException();
}

结果:A 插入成功、B插入失败
注意:这与 REQUIRED 不同,REQUIRED 的话 A 会插入失败。该 NESTED 传播类型下,父事务回滚会导致子事务也回滚,但是子事务回滚不会使父事务也回滚。

你可能感兴趣的:(Spring事务传播机制)