Skip to content
章节导航

Spring 事务

事务是一组原子操作,要么全部执行,要么全部撤销;且包含四个特性:原子、一致、隔离、持久

Spring 事务的两种实现

  • 编程式事务两种实现:TransactionTemplate(模板事务)、PlatformTransactionManager(事务管理器,使用起来比较麻烦)
  • 声明式事务:@Transaction,需要关注其使用方法、回滚规则、实现机制和失效场景

编程式事务

java
public class EcommerceAccountServiceImpl {

    /** 模板事务 */
    private final TransactionTemplate transactionTemplate;

    /**
     *  使用编程式事务 
     */
    public void addAccountUserTransactionTemplate() {

        // 第一种方式:执行事务没有返回值
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {

                try {
                    EcommerceAccount account = EcommerceAccount.builder()
                            .userId(1L)
                            .build();
                    EcommerceAccountVip accountVip = EcommerceAccountVip.builder()
                            .userId(1L)
                            .build();
                    ecommerceAccountWrapper.getMapper().insert(account);
                    ecommerceAccountVipWrapper.getMapper().insert(accountVip);
                    // 抛出异常
                    throw new Exception();
                } catch (Exception ex) {
                    status.setRollbackOnly();
                }
            }
        });

        // 第二种方式:执行事务可以有一个返回值
        transactionTemplate.execute((tx) -> {
            EcommerceAccount account = EcommerceAccount.builder()
                    .userId(1L)
                    .build();
            EcommerceAccountVip accountVip = EcommerceAccountVip.builder()
                    .userId(1L)
                    .build();
            ecommerceAccountWrapper.getMapper().insert(account);
            ecommerceAccountVipWrapper.getMapper().insert(accountVip);
            return true;
        });
    }
    
}

声明式事务

java
@Transactional(rollbackFor = Exception.class)
private void invalid() throws Exception {
}