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;
        }
    }
}
相关推荐
sheji34162 小时前
【开题答辩全过程】以 摩托车及配件售后管系统为例,包含答辩的问题和答案
java
aisifang002 小时前
SpringBoot Maven 项目 pom 中的 plugin 插件用法整理
spring boot·后端·maven
我是苏苏2 小时前
消息中间件RabbitMQ04:路由模式+死信队列的应用实践模板
java·开发语言
花无缺0002 小时前
Java开发踩坑:一次线上性能优化案例
java·开发语言·人工智能·面试
yashuk2 小时前
SpringBoot中自定义Starter
java·spring boot·后端
一只大袋鼠2 小时前
并发编程(二十三):单例模式(二):静态/非静态方法:单例内存优化关键
java·单例模式·并发编程
6+h2 小时前
【java IO】缓冲流详解
java·开发语言
爱丽_2 小时前
方法区 / 元空间:JDK 1.7 到 JDK 1.8 到底变了什么?
java·开发语言
JNU freshman2 小时前
Ceph 中与“重构/恢复/回填/重平衡”相关的参数表
java·ceph·重构