️ 【JAVA实战】手把手教你SpringBoot中事务@Transactional的正确姿势

目录

一、事务的定义

二、特点

三、应用场景

四:实战配置

五、总结:


一、事务的定义

在Java中,事务(Transaction)是指作为单个逻辑工作单元执行的一系列操作。当涉及到数据库操作时,事务确保了数据的完整性和一致性,即使在出现故障的情况下也能保证数据的安全。事务的处理通常在数据库管理系统(DBMS)层面进行,但在Java环境中,事务的管理也可以通过编程框架如Spring或Java Transaction API (JTA)来控制。

二、特点

事务具有以下四个主要特性,通常称为ACID特性:

  1. 原子性(Atomicity)

    • 事务是一个不可分割的最小工作单元,事务内的所有操作要么全部成功,要么全部失败回滚。
  2. 一致性(Consistency)

    • 事务开始之前和结束之后,数据库的完整性约束没有被破坏。这意味着事务的执行不会违反任何规则,如外键约束、唯一性约束等。
  3. 隔离性(Isolation)

    • 事务之间相互隔离,一个事务的执行不会受到其他事务的影响。根据不同的隔离级别,事务可以避免脏读、不可重复读和幻读等问题。
  4. 持久性(Durability)

    • 一旦事务提交,它对数据库所做的更改将是永久的,即使在系统故障后也应如此。

三、应用场景

事务在Java应用中通常用于以下几种情况:

  1. 多表更新

    • 当一个业务操作需要同时更新多个表时,使用事务可以确保所有更新要么一起成功,要么一起失败。
  2. 复杂业务流程

    • 在涉及多个步骤的业务流程中,如果其中一个步骤失败,事务可以回滚到开始状态,避免部分操作完成而部分未完成的情况。
  3. 并发控制

    • 在高并发环境下,事务可以帮助控制数据的并发访问,防止数据冲突和不一致。
  4. 批量操作

    • 当需要执行一系列数据库操作时,可以将其封装在一个事务中,减少网络通信次数,提高效率。
  5. 安全性

    • 事务可以提供一定程度的数据安全保护,例如在银行交易、电子商务支付等场景中,确保资金转移的准确性和安全性。

        在Java中,事务的管理可以通过手动的方式使用Connection对象的commit()rollback()方法,也可以通过Spring框架的声明式事务管理来自动处理事务边界。Spring框架允许通过注解(如@Transactional)或XML配置来控制事务的开始和结束,这大大简化了事务的管理。

四:实战配置

        Spring Boot各版本对事务管理的开启和配置方式大体上保持了一致性,但具体实现细节和默认行为可能会随版本的更新而略有不同。下面是一些关键点,说明Spring Boot不同版本中事务管理的主要区别:

Spring Boot1.X版本

  • 在Spring Boot 1.x版本中,事务管理主要通过Spring的@EnableTransactionManagement注解来显式地启用。
  • 你需要在配置类中添加@EnableTransactionManagement注解,以启动Spring的事务管理功能。
  • @Transactional注解用于标记需要事务支持的类或方法。
  • 通常还需要显式配置事务管理器,例如DataSourceTransactionManager,并将其注册到Spring容器中。

启动类配置:


/**
 * 启动服务
 */
@SpringBootApplication
@RestController
@EnableTransactionManagement //开启事务
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication .class, args);
    }
}

开启全局配置:

package com.config;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.persistence.Transient;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Title: 事务配置类
 */
@Configuration
public class TxConfigBeanName {
	@Autowired(required=true)
	@Transient
    private DataSourceTransactionManager transactionManager;


    @Bean
    public  DataSourceTransactionManager  transactionManager(DataSource dataSource)  {
        return  new  DataSourceTransactionManager(dataSource);
    }
    // 创建事务通知
    @Bean(name = "txAdvice")
    public TransactionInterceptor getAdvisor() {

        Properties properties = new Properties();
        properties.setProperty("add*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("save*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("modify*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("*Delete*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("disable*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("enable*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("handle*", "PROPAGATION_REQUIRED,-ServiceException");
        // properties.setProperty("*", "PROPAGATION_REQUIRED,-ServiceException,readOnly");

        TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties);
        return tsi;

    }

    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*Service", "*ServiceImpl");
        creator.setProxyTargetClass(true);
        return creator;
    }
}

@Transactional应用

 @Transactional(rollbackFor = Exception.class)
    public void save(test vo) {
        saveTest(vo);//保存主表
        saveItem(vo.getItem());//保存子表
    }

Spring Boot 2.x 版本

  • Spring Boot 2.x系列进一步增强了自动配置能力,对于事务管理也是如此。
  • 默认情况下,如果应用程序使用了Spring Data JPA或其他Spring Data模块,Spring Boot会自动配置JpaTransactionManager或相应的事务管理器。
  • @EnableTransactionManagement注解在大多数情况下不再是必需的,因为事务管理的自动配置会自动包含它。
  • 开发者仍然可以在需要的地方使用@Transactional注解来控制事务的范围和行为。

开启全局配置:

package com.config;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.persistence.Transient;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Title: 事务配置类
 */
@Configuration
public class TxConfigBeanName {
	@Autowired(required=true)
	@Transient
    private DataSourceTransactionManager transactionManager;


    @Bean
    public  DataSourceTransactionManager  transactionManager(DataSource dataSource)  {
        return  new  DataSourceTransactionManager(dataSource);
    }
    // 创建事务通知
    @Bean(name = "txAdvice")
    public TransactionInterceptor getAdvisor() {

        Properties properties = new Properties();
        properties.setProperty("add*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("save*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("modify*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("*Delete*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("disable*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("enable*", "PROPAGATION_REQUIRED,-ServiceException");
        properties.setProperty("handle*", "PROPAGATION_REQUIRED,-ServiceException");
        // properties.setProperty("*", "PROPAGATION_REQUIRED,-ServiceException,readOnly");

        TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties);
        return tsi;

    }

    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*Service", "*ServiceImpl");
        creator.setProxyTargetClass(true);
        return creator;
    }
}

@Transactional应用

 @Transactional(rollbackFor = Exception.class)
    public void save(test vo) {
        saveTest(vo);//保存主表
        saveItem(vo.getItem());//保存子表
    }

五、总结:

        以上即为SpringBoot的事务开启、配置与使用方式!对你有所帮助,关注博主或点个赞再走吧!更多资源也可关注微信公众号获取!

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值