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;
        }
    }
}
相关推荐
郑州光合科技余经理14 分钟前
PHP构建:支撑欧美澳市场的同城生活服务平台开发
java·开发语言·数据库·uni-app·php·排序算法·生活
超级大只老咪7 小时前
数组相邻元素比较的循环条件(Java竞赛考点)
java
小浣熊熊熊熊熊熊熊丶7 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
毕设源码-钟学长8 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案
java·eclipse
啃火龙果的兔子8 小时前
JDK 安装配置
java·开发语言
星哥说事8 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
派大鑫wink8 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
xUxIAOrUIII8 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home8 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
醇氧8 小时前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea