@Transactional注解详细使用

时间:2022-06-03 11:28:14

一、@Transactional 注解使用

  • @Transactional  注解只能用在public 方法上,如果用在protected或者private的方法上,不会报错,但是该注解不会生效。
  • @Transactional注解只能回滚非检查型异常,具体为RuntimeException及其子类。
  • 使用rollbackFor 属性来定义回滚的异常类型,使用 propagation 属性定义事务的传播行为。如:
 @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
//回滚Exception类的异常,事务的传播行为支持当前事务,如果没有事务,那么会创建一个事务。
  • @Transactional注解不能回滚被try{}catch() 捕获的异

二、 Spring事务的传播行为

    1)PROPAGATION_REQUIRED   :  支持当前事务,如果当前没有事务,则创建一个事务,这是最常见的选择。

2)PROPAGATION_SUPPORTS   :  支持当前事务,如果当前没有事务,就以非事务来执行。

3)PROPAGATION_MANDATORY  :  支持当前事务,如果没有当前事务,就抛出异常。

4)PROPAGATION_REQUIRES_NEW :   新建事务,如果当前存在事务,就把当前事务挂起。

5)PROPAGATION_NOT_SUPPORTED :  以非事务执行操作,如果当前存在事务,则当前事务挂起。

6)PROPAGATION_NEVER :  以非事务方式执行,如果当前存在事务,则抛出异常。

7)PROPAGATION_NESTED :  如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED 类似的操作。

三、开发案例

workflow服务, 设置的事务传播行为为 :REQUIED

@Transactional注解详细使用

payment服务添加注解: 回滚所有的异常。

@Transactional注解详细使用

Fegin:

package com.hand.hcf.app.workflow.client.extraApi;

import com.hand.hcf.app.workflow.approval.dto.CashTransactionDataCreateCO;
import com.hand.hcf.app.workflow.brms.dto.ApprovalDocumentWithValuesCODTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam; import java.util.List; /**
* PaymentInterface
*
* @Auther: zhengbing.zhang
* @Date:2019/8/19
* @remark
*/
@FeignClient(
name = "${hcf.application.payment.name:fec-payment}",
url = "${hcf.application.payment.url:}",
contextId = "PaymentInterface"
)
public interface PaymentInterface { @PostMapping({"/api/implement/payment/cash/transactionData/batch/v2"})
void saveTransactionDatasBatch(@RequestBody List<ApprovalDocumentWithValuesCODTO> cashTransactionDatas); @GetMapping("/api/acp/requisition/header/update/status/by/documentNumber")
void updateDocumentStatusByDocumentNumber(
@RequestParam("documentNumber") String documentNumber
,@RequestParam("status") Integer status); }

测试:

workflow 调用payment服务的saveTransactionDatasBatch方法, 然Payment服务报错,workflow服务收到错误后回滚:

@Transactional注解详细使用