spring 项目 手动提交事务

文章详细描述了如何在SpringMVC中使用@Autowired注入TransactionManager和TransactionDefinition,通过commitTransA方法演示了如何执行一个带有回滚的事务操作,最终结果显示仅A记录被插入。
    @Autowired
    private PlatformTransactionManager manager;

    @Autowired
    private TransactionDefinition transactionDefinition;


    @RequestMapping("/commitTransA")
    public String commitTransA() {
        TransactionStatus transaction = manager.getTransaction(transactionDefinition);
        tbTransMapper.insertTransInfo("A");
        transaction.isCompleted();
        manager.commit(transaction);
        int i = 1 / 0;

        tbTransMapper.insertTransInfo("B");
        return "事务A 提交成功、事务B 回滚成功";
    }

效果展示

只有A被插入
### 如何在 Spring Batch 中手动提交事务Spring Batch 中,默认情况下,事务管理是由框架自动完成的。然而,在某些场景下可能需要手动控制事务的行为。通过自定义 `TransactionTemplate` 或者直接操作 `PlatformTransactionManager`,可以实现手动提交事务的功能。 以下是具体的配置和示例: #### 1. 添加必要的依赖 为了使用 Spring Batch 和事务功能,需确保项目中包含以下 Maven 依赖[^3]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` #### 2. 自定义 TransactionTemplate 实现手动提交事务 可以通过注入 `TransactionTemplate` 来手动控制事务行为。下面是一个简单的例子: ```java import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; @EnableBatchProcessing public class ManualTransactionConfig { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private TransactionTemplate transactionTemplate; @Bean public Job manualTransactionJob() { return jobBuilderFactory.get("manualTransactionJob") .start(manualTransactionStep()) .build(); } @Bean public Step manualTransactionStep() { return stepBuilderFactory.get("manualTransactionStep") .tasklet((stepContribution, chunkContext) -> { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { try { // 执行业务逻辑 System.out.println("执行数据库更新..."); // 如果发生异常,则回滚事务 if (true /* 假设某个条件 */) { throw new RuntimeException("模拟错误"); } } catch (Exception e) { status.setRollbackOnly(); // 设置回滚 throw e; } } }); return RepeatStatus.FINISHED; }) .build(); } } ``` 在此代码片段中,`TransactionTemplate` 被用来显式地包裹事务逻辑,并允许开发者决定何时提交或回滚事务[^4]。 #### 3. 使用 PlatformTransactionManager 进行更细粒度的手动控制 如果需要更加灵活的事务控制方式,可以直接使用 `PlatformTransactionManager` 接口来获取当前事务的状态并进行提交或回滚。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; @Component public class CustomTransactionService { @Autowired private DataSourceTransactionManager transactionManager; public void performManualTransaction() { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("CustomTx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = transactionManager.getTransaction(def); try { // 执行业务逻辑 System.out.println("正在执行手动事务..."); // 提交事务 transactionManager.commit(status); } catch (RuntimeException ex) { // 发生异常时回滚事务 transactionManager.rollback(status); throw ex; } } } ``` 此方法提供了对事务生命周期的完全掌控能力,适合复杂的业务需求[^5]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值