Spring框架的事务管理

引言

在企业级应用开发中,事务管理是一个至关重要的环节,它确保了数据的一致性和完整性。Spring 框架为我们提供了强大而灵活的事务管理功能,能够帮助开发者更轻松地处理复杂的事务场景。本文将深入探讨 Spring 框架的事务管理,包括相关的类和 API,以及声明式事务管理的实现方式,并结合具体代码示例进行详细解释。

1. Spring 框架的事务管理相关的类和 API

1.1 PlatformTransactionManager 接口

PlatformTransactionManager 是 Spring 框架中用于管理事务的核心接口,它定义了事务的基本操作,如提交和回滚。该接口有具体的实现类,我们需要根据不同的持久层框架选择合适的实现类。

接口方法
  • void commit(TransactionStatus status):用于提交事务。
  • void rollback(TransactionStatus status):用于回滚事务。
实现类选择
  • DataSourceTransactionManager:如果使用 Spring 的 JDBC 模板或者 MyBatis 框架,应选择这个实现类。因为这些框架都是基于数据源(DataSource)进行数据库操作的,DataSourceTransactionManager 可以很好地与数据源集成,管理事务。
  • HibernateTransactionManager:当使用 Hibernate 框架时,需要选择这个实现类。它专门为 Hibernate 的事务管理而设计,能够与 Hibernate 的会话(Session)和事务机制无缝对接。

1.2 TransactionDefinition 接口

TransactionDefinition 接口定义了事务的一些基本属性,包括事务隔离级别和事务传播行为。

事务隔离级别

事务隔离级别用于控制多个事务之间的可见性和并发访问。常见的隔离级别有:

  • ISOLATION_DEFAULT:使用数据库的默认隔离级别。
  • ISOLATION_READ_UNCOMMITTED:允许读取未提交的数据,可能会导致脏读、不可重复读和幻读问题。
  • ISOLATION_READ_COMMITTED:只能读取已提交的数据,避免了脏读,但仍可能出现不可重复读和幻读。
  • ISOLATION_REPEATABLE_READ:保证在同一个事务中多次读取同一数据的结果是一致的,避免了脏读和不可重复读,但仍可能出现幻读。
  • ISOLATION_SERIALIZABLE:最高的隔离级别,所有事务依次执行,避免了脏读、不可重复读和幻读,但会降低并发性能。

事务传播行为

事务传播行为定义了在一个事务方法调用另一个事务方法时,事务应该如何处理。常见的传播行为有:

  • PROPAGATION_REQUIRED:如果当前存在事务,则加入该事务;如果不存在,则创建一个新的事务。
  • PROPAGATION_SUPPORTS:如果当前存在事务,则加入该事务;如果不存在,则以非事务方式执行。
  • PROPAGATION_MANDATORY:如果当前存在事务,则加入该事务;如果不存在,则抛出异常。
  • PROPAGATION_REQUIRES_NEW:无论当前是否存在事务,都创建一个新的事务,并挂起当前事务。
  • PROPAGATION_NOT_SUPPORTED:以非事务方式执行,如果当前存在事务,则挂起该事务。
  • PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
  • PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务中执行;如果不存在,则创建一个新的事务。

 2. Spring 框架声明式事务管理

2.1、XML 配置方式

1. 配置文件

  • jdbc.properties:存储数据库连接信息,包括驱动类名、URL、用户名和密码。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
  • applicationContext.xml:核心配置文件,主要完成以下配置:
    • 加载属性文件:通过 <context:property - placeholder> 加载 jdbc.properties
    • 配置数据源:使用 Druid 数据源,将属性文件中的配置注入。
    • 配置平台事务管理器:使用 DataSourceTransactionManager,并关联数据源。
    • 配置事务通知:通过 <tx:advice> 定义事务属性,如 pay 方法使用事务,find* 方法只读。
    • 配置 AOP:通过 <aop:config> 定义切入点和通知的关联。
    • 配置 Service 和 Dao:将 Service 和 Dao 作为 Bean 注册到 Spring 容器中,并进行依赖注入。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 加载属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置平台事务管理器 -->
    <bean id="transactionManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- pay 方法使用事务 -->
            <tx:method name="pay" isolation="DEFAULT" propagation="REQUIRED"/>
            <!-- find 开头的方法只读 -->
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置 AOP -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" 
                    pointcut="execution(public * com.qcbyjy.demo4.AccountServiceImpl.pay(..))"/>
    </aop:config>

    <!-- 配置 Service -->
    <bean id="accountService" class="com.qcbyjy.demo1.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!-- 配置 Dao -->
    <bean id="accountDao" class="com.qcbyjy.demo1.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

2.Java类 

  • AccountDao.java:定义数据访问接口,包含 outMoneyinMoney 和 findMoney 方法。
package com.qcbyjy.demo1;

public interface AccountDao {
    void outMoney(String out, double money);
    void inMoney(String in, double money);
    double findMoney(String name);
}
  • AccountDaoImpl.java:实现 AccountDao 接口,通过 JdbcDaoSupport 进行数据库操作。
package com.qcbyjy.demo1;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public void outMoney(String out, double money) {
        String sql = "update account set money=money-? where name=?";
        this.getJdbcTemplate().update(sql, money, out);
    }

    @Override
    public void inMoney(String in, double money) {
        String sql = "update account set money=money+? where name=?";
        this.getJdbcTemplate().update(sql, money, in);
    }

    @Override
    public double findMoney(String name) {
        String sql = "select money from account where name=?";
        return this.getJdbcTemplate().queryForObject(sql, Double.class, name);
    }
}
  • AccountService.java:定义业务服务接口,包含 pay 和 checkBalance 方法。
package com.qcbyjy.demo1;

public interface AccountService {
    void pay(String out, String in, double money);
    double checkBalance(String name);
}
  • AccountServiceImpl.java:实现 AccountService 接口,调用 AccountDao 完成业务逻辑。
package com.qcbyjy.demo1;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void pay(String out, String in, double money) {
        accountDao.outMoney(out, money);
        // 模拟异常,测试事务回滚
        // int a = 1/0;
        accountDao.inMoney(in, money);
    }

    @Override
    public double checkBalance(String name) {
        return accountDao.findMoney(name);
    }
}

3.测试 

package com.qcbyjy.test.demo1;

import com.qcbyjy.demo1.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo1 {
    @Test
    public void testXmlTransaction(){
        ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService =(AccountService) context.getBean("accountService");
        System.out.println("XML配置方式事务测试...");
        try {
            accountService.pay("aaa", "ccc", 100);
            System.out.println("转账成功!");
        } catch (Exception e) {
            System.out.println("转账失败,事务已回滚:" + e.getMessage());
        }
    }
}

4. 重要知识点

  • 事务通知和 AOP 配置:通过 <tx:advice> 定义事务属性,再通过 <aop:config> 将事务通知应用到指定的切入点,实现事务的织入。
  • 属性占位符<context:property - placeholder> 可以方便地加载属性文件,将配置信息从 XML 文件中分离出来,提高配置的可维护性。

2.2、XML + 注解方式

1. 配置文件

  • applicationContext_1.xml:主要完成以下配置:
    • 开启注解扫描:通过 <context:component - scan> 扫描指定包下的注解组件。
    • 加载属性文件:同 XML 配置方式。
    • 配置数据源和事务管理器:同 XML 配置方式。
    • 配置 Jdbc 模板:为 Dao 层提供数据库操作模板。
    • 开启事务注解支持:通过 <tx:annotation - driven> 开启 @Transactional 注解的支持。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.qcbyjy.demo2"/>

    <!-- 加载属性文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置平台事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置Jdbc模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启事务注解支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

2. Java 类

  • AccountDao.java:同 XML 配置方式。
  • AccountDaoImpl.java:使用 @Repository 注解将该类注册为 Spring Bean,并通过 @Autowired 注入 JdbcTemplate
package com.qcbyjy.demo2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImpl  implements AccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     *付款
     *@paramout
     *@parammoney
     */
    public void outMoney(String out,double money){
        String sql="update account set money=money - ? where name = ?";
        jdbcTemplate.update(sql,money,out);
    }
    /**
     *收款
     *@paramin
     *@parammoney
     */
    public void inMoney(String in,double money){
        String sql="update account set money=money +? where name= ?";
        jdbcTemplate.update(sql,money,in);

    }

}
  • AccountService.java:同 XML 配置方式。
  • AccountServiceImpl.java:使用 @Service 注解将该类注册为 Spring Bean,并使用 @Transactional 注解定义事务属性。
package com.qcbyjy.demo2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(isolation = Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

/**
 *转账方法
 *@paramout付款人
 *@paramin收款人
 *@parammoney金额
 */
    public void pay(String out,String in,double money){
        accountDao.outMoney(out,money);
        // 模拟异常
//         int a = 1/0;
        accountDao.inMoney(in,money);
    }

}

3.测试

package com.qcbyjy.test.demo2;

import com.qcbyjy.demo2.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo2 {
    @Test
    public void testAnnotationTransaction(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext_1.xml");
        AccountService accountService=context.getBean(AccountService.class);
        System.out.println("XML+注解方式事务测试...");
        try {
            accountService.pay("ccc", "aaa", 100);
            System.out.println("转账成功!");
        } catch (Exception e) {
            System.out.println("转账失败,事务已回滚:" + e.getMessage());
        }
    }
}

4. 重要知识点

  • 注解扫描<context:component - scan> 可以自动扫描指定包下的 @Component@Repository@Service 和 @Controller 注解的类,并将它们注册为 Spring Bean。
  • @Transactional 注解:用于定义事务属性,如隔离级别、传播行为、是否只读等。可以应用在类或方法上,应用在类上时,该类的所有公共方法都将应用该事务属性。

 2.3、纯注解方式

1. Java 配置类

  • SpringConfig.java:使用 @Configuration 注解将该类标记为配置类,通过 @ComponentScan 扫描指定包下的注解组件,使用 @EnableTransactionManagement 开启事务注解支持,并通过 @Bean 方法定义数据源、Jdbc 模板和事务管理器。
package com.qcbyjy.demo3;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;


@Configuration
@ComponentScan(basePackages = "com.qcbyjy.demo3")
@EnableTransactionManagement
public class SpringConfig {

    @Bean(name="dataSource")
    public DataSource dataSource() {
        // 创建连接池对象,Spring框架内置了连接池对象
        DruidDataSource dataSource = new DruidDataSource();
        // 设置4个参数
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_db?useSSL=false&characterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("12345");
        return dataSource;
    }

    @Resource(name="dataSource")
    @Bean(name="jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        JdbcTemplate template =new JdbcTemplate(dataSource);
        return template;
    }

    @Resource(name="dataSource")
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource);
        return manager;
    }

//    @Bean
//    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
//        return new JdbcTemplate(dataSource);
//    }

//    @Bean
//    public PlatformTransactionManager transactionManager(DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }
}

2. Java 类

  • AccountDao.javaAccountDaoImpl.javaAccountService.java 和 AccountServiceImpl.java:同 XML + 注解方式。

3.测试

package com.qcbyjy.test.Demo3;

import com.qcbyjy.demo3.AccountService;
import com.qcbyjy.demo3.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo3 {
    @Test
    public void testPureAnnotationTransaction() {
     AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
     AccountService accountService=context.getBean(AccountService.class);

        System.out.println("纯注解方式事务测试...");
        try {
            accountService.pay("aaa", "ccc", 1000);
            System.out.println("转账成功!");
        } catch (Exception e) {
            System.out.println("转账失败,事务已回滚:" + e.getMessage());
        }
        context.close();
    }
}

4. 重要知识点

  • Java 配置类:使用 @Configuration 注解的类可以替代 XML 配置文件,通过 @Bean 方法定义 Bean,提高配置的灵活性和可维护性。
  • @EnableTransactionManagement:开启 Spring 的事务注解支持,使得 @Transactional 注解生效。

4.事务特性验证

三种方式都可以通过取消注释模拟异常的代码(int a = 1/0;)来测试事务回滚功能。每次测试前后会打印账户余额,验证事务是否正常工作。同时,需要创建 spring_db 数据库和 account 表,并初始化张三和李四的账户余额为 1000。

5.总结

  • XML 配置方式:适合于对配置细节有严格要求,且团队对 XML 配置比较熟悉的场景。通过 XML 可以清晰地定义事务的各个方面,但配置文件可能会变得冗长和复杂。
  • XML + 注解方式:结合了 XML 配置的灵活性和注解的简洁性,XML 负责全局配置,注解负责局部配置,是一种比较常用的方式。
  • 纯注解方式:适合于追求代码简洁性和开发效率的场景,完全基于 Java 配置和注解,减少了 XML 配置文件的使用,但对开发者的 Java 配置能力要求较高。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值