Spring学习第四天------2021-07-16-声明式事务管理

声明式事务管理

1.检查项目中是否已经有Spring-tx的jar包

【注意】一般在导入spring-jdbc的时候默认导入了
在这里插入图片描述
如果不放心,可自己导入

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.0.5.RELEASE</version>
</dependency>

2.修改命名空间

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">

在这里插入图片描述

3.在beans.xml中配置事务管理

 <!--配置事务==================必然拥有-->
    <bean id="dataSourceTransactionManager" 			       			  												class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     	<property name="dataSource" ref="dataSource"></property>
    </bean>

以下有所区分:分为注解版本和xml版本

注解版本

开启事务
 <!--开启事务===============注解版本-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>
在需要的service层对应的类上方添加注解@Transactional
@Transactional
    void updateSal(int i1, int i2, double sal);

XML版本

配置事务切面
 <!--配置事务切面===================XML版本-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.zx.service.impl.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>
事务的xml配置
 <!--事务的xml配置===================XML版本-->
    <tx:advice id="txadvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值