Spring5-事务操作

事务操作的四个特性:重点掌握

原子性

一致性

隔离性

永久性

问题引入:

 事务操作过程:

编程式事务管理:

声明式事务管理(使用)

基于注解方式:

1、在 Spring 进行声明式事务管理,底层使用 AOP 原理

2、Spring 事务管理 API

 实现步骤:

<!--1、在 spring 配置文件配置事务管理器-->
<!--创建事务管理器-->
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!--2、在 spring 配置文件,开启事务注解-->
<!--(1)在 spring 配置文件引入名称空间 tx-->
<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">
<!--(2)开启事务注解-->
<!--开启事务注解-->
<tx:annotation-driven transactionmanager="transactionManager"></tx:annotation-driven>
<!--3、在 service 类上面(或者 service 类里面方法上面)添加事务注解-->
<!--(1)@Transactional,这个注解添加到类上面,也可以添加方法上面-->
<!--(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务-->
<!--(3)如果把这个注解添加方法上面,为这个方法添加事务-->

基于xml进行事务管理(可以帮助了解事务功能实现的原理)

<!--1 创建事务管理器-->
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!--前面第一步比较简单,要想进行事务管理就要先得到事务管理器-->

<!--2 配置通知:如何进行增强;
    这里是相当于进行事务增强;
    我们得到了事务管理器之后,我们应该对事务管理器进行相应的设置;
    设置传播行为参数;
-->
<tx:advice id="txadvice">
 <!--配置事务参数-->
 <tx:attributes>
 <!--指定哪种规则的方法上面添加事务-->
 <tx:method name="accountMoney" propagation="REQUIRED"/>
 <!--<tx:method name="account*"/>-->
 </tx:attributes>
</tx:advice>



<!--3 配置切入点和切面
    
-->
<aop:config>
     <!--配置切入点
         哪个类里面的方法是切入点
     -->
     <aop:pointcut id="pt" expression="execution(* 
com.atguigu.spring5.service.UserService.*(..))"/>
     <!--配置切面
        切面是将通知应用到切入点的一个动作
        在这里:
        通知是上面设置的事务通知
        切入点也是上面设置的,所以将事务通知和切入点绑定起来
        -->
     <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小馨java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值