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;
        }
    }
}
相关推荐
之歆1 天前
Spring AI入门到实战到原理源码-MCP
java·人工智能·spring
yangminlei1 天前
Spring Boot3集成LiteFlow!轻松实现业务流程编排
java·spring boot·后端
qq_318121591 天前
互联网大厂Java面试故事:从Spring Boot到微服务架构的技术挑战与解答
java·spring boot·redis·spring cloud·微服务·面试·内容社区
计算机毕设VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue医院设备管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
J_liaty1 天前
Spring Boot整合Nacos:从入门到精通
java·spring boot·后端·nacos
Mr__Miss1 天前
保持redis和数据库一致性(双写一致性)
数据库·redis·spring
阿蒙Amon1 天前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
daidaidaiyu1 天前
Spring IOC 源码学习 一文学习完整的加载流程
java·spring
Knight_AL1 天前
Spring 事务传播行为 + 事务失效原因 + 传播行为为什么不用其他模式
数据库·sql·spring
2***d8851 天前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端