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;
        }
    }
}
相关推荐
野生的码农20 小时前
码农的妇产科实习记录
android·java·人工智能
毕设源码-赖学姐21 小时前
【开题答辩全过程】以 高校人才培养方案管理系统的设计与实现为例,包含答辩的问题和答案
java
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
一起努力啊~1 天前
算法刷题-二分查找
java·数据结构·算法
小途软件1 天前
高校宿舍访客预约管理平台开发
java·人工智能·pytorch·python·深度学习·语言模型
J_liaty1 天前
Java版本演进:从JDK 8到JDK 21的特性革命与对比分析
java·开发语言·jdk
+VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
daidaidaiyu1 天前
一文学习和实践 当下互联网安全的基石 - TLS 和 SSL
java·netty
hssfscv1 天前
Javaweb学习笔记——后端实战2_部门管理
java·笔记·学习
NE_STOP1 天前
认识shiro
java