1. 程式人生 > >搞懂spring事務

搞懂spring事務

point final ack nconf pan ger static intercept author

最近一個官網的項目,我在service層有兩個添加數據的操作,很意外報錯了,然後就研究到了事務

之前只是知道聲明式事務和編程式事務,編程式的事務顯得比較麻煩,一般都是使用聲明式事務..

spring提供了很多種配置方式:

編程式事務:

  開啟事務;

  try{

    更新或添加操作;

    提交;

  }catch(..){

    回滾;

  }

聲明式事務:

  提交,回滾的操作寫在了一個代理類裏頭,在執行事務方法之前開啟事務,在執行完方法之前提交或者回滾事務

  

1 給每個bean(service類)配置一個代理類

2 所有service類公用一個代理類

3 攔截器(aop的方式)

4 全註解(在service類加上Transaction)

註 : spring只對runtiomException才會回滾(經測試的) 提供了對應的屬性設置異常類型

下面是我項目裏頭事務的配置 (config配置呢) :

/**
 * 註解聲明式事務配置(相當於上述的aop方式的配置)
 * @author liyong
 *
 */
@Configuration
public class TxAdviceTransactionConfig {
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.mike.mihome.*.service..*.*(..))";
    
    @Autowired
    private PlatformTransactionManager transactionManager;
    
    @Bean
    public TransactionInterceptor txAdvice(){
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        
        //只讀事務,不做更新操作
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        
        //當前存在事務就使用當前事務,當前不存在事務就創建一個新的事務
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
//        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class))); //設置異常類型
requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); requiredTx.setTimeout(10000); Map<String, TransactionAttribute> txMap = new HashMap<String, TransactionAttribute>(); txMap.put("query*", readOnlyTx); txMap.put("get*", readOnlyTx); txMap.put("*", requiredTx); source.setNameMap(txMap); TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source); return txAdvice; } @Bean public Advisor txAdviceAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(AOP_POINTCUT_EXPRESSION); return new DefaultPointcutAdvisor(pointcut, txAdvice()); } }

  

搞懂spring事務