站内搜索

搜索

06-02 13:26
05-31 17:11

Spring事务实现的几种方式

47

主题

38

点数

151

积分

地衡测影

积分
151

柴到了

发表于 2025-3-21 02:11:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x

一、前言

1.、事务几种实现方式
(1)编程式事务管理对基于 POJO 的应用来说是唯一选择。我们需要在代码中调用beginTransaction()、commit()、rollback()等事务管理相关的方法,这就是编程式事务管理。
(2)基于 TransactionProxyFactoryBean的声明式事务管理
(3)基于 @Transactional 的声明式事务管理
(4)基于Aspectj AOP配置事务

二、编程式事务管理

2.1 transactionTemplate

此种方式是自动的事务管理,无需手动开启、提交、回滚。

<!-- 配置事务管理器 ,封装了所有的事务操作,依赖于连接池 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
</bean>

2.配置事务模板对象

<!-- 配置事务模板对象 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
            <property name="transactionManager" ref="transactionManager"></property>
</bean>

2.2 PlatformTransactionManager

使用 事务管理器 PlatformTransactionManager 对象,PlatformTransactionManager是DataSourceTransactionManager实现的接口类
此方式,可手动开启、提交、回滚事务。
1.只需要:配置事务管理


<!-- 配置事务管理 ,封装了所有的事务操作,依赖于连接池 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
</bean>

三、声明式事务管理

3.1 基于Aspectj AOP开启事务

1.配置事务通知

<!--       配置事务增强 -->
       <tx:advice id="txAdvice"  transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
       </tx:advice>

2.配置织入


<!--       aop代理事务。扫描 cn.sys.service 路径下所有的方法 -->
       <aop:config>
       <!--     扫描 cn.sys.service 路径下所有的方法,并加入事务处理 -->
        <aop:pointcut id="tx"  expression="execution(* cn.sys.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tx" />
      </aop:config>

3.完整例子

<?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:aop="http://www.springframework.org/schema/aop"
       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-3.2.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.2.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

       <!-- 创建加载外部Properties文件对象 -->
       <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:dataBase.properties"></property>
       </bean>
    <!-- 引入redis属性配置文件 -->
    <import resource="classpath:redis-context.xml"/>

       <!-- 配置数据库连接资源 -->
       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" scope="singleton">
            <property name="driverClassName" value="${driver}"></property>
            <property name="url" value="${url}"></property>
            <property name="username" value="${username}"></property>
            <property name="password" value="${password}"></property>

            <property name="maxActive" value="${maxActive}"></property>
            <property name="maxIdle" value="${maxIdle}"></property>
            <property name="minIdle" value="${minIdle}"></property>
            <property name="initialSize" value="${initialSize}"></property>
            <property name="maxWait" value="${maxWait}"></property>
            <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"></property>
            <property name="removeAbandoned" value="${removeAbandoned}"></property>

            <!-- 配置sql心跳包 -->
            <property name= "testWhileIdle" value="true"/>
            <property name= "testOnBorrow" value="false"/>
            <property name= "testOnReturn" value="false"/>
            <property name= "validationQuery" value="select 1"/>
            <property name= "timeBetweenEvictionRunsMillis" value="60000"/>
            <property name= "numTestsPerEvictionRun" value="${maxActive}"/>
       </bean>

<!--创建SQLSessionFactory对象  -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="configLocation" value="classpath:MyBatis_config.xml"></property>
       </bean>

       <!-- 创建MapperScannerConfigurer对象 -->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="cn.sys.dao"></property>
       </bean>

       <!-- 配置扫描器   IOC 注解 -->
       <context:component-scan base-package="cn.sys" />

       <!-- 配置事务管理 ,封装了所有的事务操作,依赖于连接池 -->
       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
       </bean>

        <!-- 配置事务模板对象 -->
       <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
            <property name="transactionManager" ref="transactionManager"></property>
        </bean>

<!--      配置事务增强 -->
       <tx:advice id="txAdvice"  transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
       </tx:advice>

<!--     aop代理事务 -->
       <aop:config>
        <aop:pointcut id="tx"  expression="execution(* cn.sys.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tx" />
      </aop:config>
</beans>

这样就算是给 cn.sys.service下所有的方法加入了事务
也可以用springboot的配置类方式:

package com.junjie.test;

@Configurationpublic 
class TxAnoConfig {    
    /*事务拦截类型*/    
    @Bean("txSource")
    public TransactionAttributeSource transactionAttributeSource() {   
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); 
        /*只读事务,不做更新操作*/        
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, Collections.singletonList(new RollbackRuleAttribute(Exception.class)));   
        requiredTx.setTimeout(60);   
        Map<String, TransactionAttribute> txMap = new HashMap<>();   
        txMap.put("*", requiredTx);  
        source.setNameMap(txMap);    
        return source; 
    }   
    /**     * 切面拦截规则 参数会自动从容器中注入     */    
    @Bean 
    public AspectJExpressionPointcutAdvisor pointcutAdvisor(TransactionInterceptor txInterceptor) { 
        AspectJExpressionPointcutAdvisor pointcutAdvisor = new AspectJExpressionPointcutAdvisor();  
        pointcutAdvisor.setAdvice(txInterceptor);    
        pointcutAdvisor.setExpression("execution (* com.cmb..*Controller.*(..))");   
        return pointcutAdvisor;   
    } 
    /*事务拦截器*/ 
    @Bean("txInterceptor")   
    TransactionInterceptor getTransactionInterceptor(PlatformTransactionManager tx) {    
        return new TransactionInterceptor(tx, transactionAttributeSource()); 
    }
}

3.2 基于注解的 @Transactional 的声明式事务管理

@Transactional
public int saveRwHist(List list) {
    return rwDao.saveRwHist(list);
}

这个注解的开启需要在spring.xml里加上一个开启注解事务的配置四、总结

以上的开启事务方式,仅需要了解即可,如今在工作中,一般不会用到这几种方式,过于繁琐。一般都是直接用springboot自带的@Transactional 注解,就可以完成这些事务管理操作。

温馨提示:看帖回帖是一种美德,您的每一次发帖、回帖都是对论坛最大的支持,谢谢! [这是默认签名,点我更换签名]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入社群

加入社群

Pixtech

Powered by Pixtech

© 2025 Pixtech Team.