SpringBoot中如何手动开启事务

这里写自定义目录标题
  • [一、使用 TransactionTemplate](#一、使用 TransactionTemplate)
    • [1、配置 TransactionTemplate](#1、配置 TransactionTemplate)
    • [2、使用 TransactionTemplate](#2、使用 TransactionTemplate)
  • [二、使用 PlatformTransactionManager 直接管理事务](#二、使用 PlatformTransactionManager 直接管理事务)
    • [1、注入 PlatformTransactionManager](#1、注入 PlatformTransactionManager)

在Spring Boot中,虽然大多数情况下推荐使用@Transactional注解来管理事务,但有时需要更灵活地手动控制事务。这可以通过TransactionTemplate或PlatformTransactionManager来实现

一、使用 TransactionTemplate

TransactionTemplate是Spring提供的一个模板类,用于简化事务管理。

1、配置 TransactionTemplate

(首先,确保你的项目已经配置了数据源和事务管理器(Spring Boot通常会自动配置这些))。

复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

@Configuration
public class TransactionConfig {

    @Bean
    public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
        return new TransactionTemplate(transactionManager);
    }
}

2、使用 TransactionTemplate

在需要手动管理事务的服务类中注入并使用TransactionTemplate:

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class MyService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    public void saveData() {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(org.springframework.transaction.TransactionStatus status) {
                try {
                    // 伪代码
                    // myRepository.save(new MyEntity("Data 1"));
                    // myRepository.save(new MyEntity("Data 2"));
                    
                    // Simulate an exception to trigger a rollback
                    if (true) {
                        throw new RuntimeException("Simulated exception");
                    }

                    // myRepository.save(new MyEntity("Data 3"));
                } catch (RuntimeException e) {
                    // Rollback transaction if exception occurs
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }
}

二、使用 PlatformTransactionManager 直接管理事务

PlatformTransactionManager接口提供了更细粒度的事务控制,适用于需要复杂事务管理的场景。

1、注入 PlatformTransactionManager

在需要手动管理事务的服务类中注入PlatformTransactionManager:

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class MyService {

    @Autowired
    private PlatformTransactionManager transactionManager;

    public void performTransactionalOperation() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setName("myTransaction");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            // Perform database operations here
            // myRepository.save(new MyEntity("Data 1"));
            // myRepository.save(new MyEntity("Data 2"));
            
            // Simulate an exception to trigger a rollback
            if (true) {
                throw new RuntimeException("Simulated exception");
            }

            // myRepository.save(new MyEntity("Data 3"));

            // Commit transaction
            transactionManager.commit(status);
        } catch (RuntimeException e) {
       
            transactionManager.rollback(status);
            throw e;
        }
    }
}
相关推荐
程序员清风17 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林55118 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
NE_STOP21 小时前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
洋洋技术笔记1 天前
Spring Boot配置管理最佳实践
spring boot
华仔啊1 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing1 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家2 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java