Spring学习记录—事务操作

前言

JAVA EE三层结构:WEB层、Service层、Dao层
在这里插入图片描述
service注入dao,dao注入JdbcTemplate, JdbcTemplate注入DataSource

事务过程:
1、开启事务
2、执行过程
3、没有发生异常,提交事务
4、出现异常,回滚事务

底层是AOP

一、Spring事务管理介绍

1、将事务添加到JAVAEE三层结构的Service层
2、有编程式事务管理和声明式事务管理
3、声明式事务管理:注解方式、xml方式
4、Spring进行声明式事务管理,底层使用AOP原理
5、Spring事务管理API:
提供一个接口,代表事务管理器
在这里插入图片描述

二、注解声明式事务管理

1.spring配置文件配置事务管理器

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

2.在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">

开启事务注解

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

3、在service上面(获取service类里面方法上面)添加事务注解

(1)@Transactional,可以添加到类上面或者方法上面
(2 )类上面,类里面所有方法都添加了事务
(3 )方法上面,只给方法添加事务

三、声明式事务管理参数配置

1、在service类上面添加注解@Transactional,在注解里面可以配置事务相关参数

在这里插入图片描述

(1) propagation:事务传播行为

多事务方法直接进行调用,这个过程中事务时如何进行管理的
七种事务传播行为
在这里插入图片描述在这里插入图片描述
参考博客:https://blog.csdn.net/weixin_39625809/article/details/80707695

(2)isolation:事务隔离级别

三大读问题:脏读、幻读、不可重复读
通过事务隔离性来解决读问题

(3)timeout:超时时间

事务需要在一定时间内进行提交,否则回滚
默认值-1,无限大

(4)readOnly:是否只读

默认值为false

(5)rollbackfor:回滚

设置出现哪些异常进行回滚

(6)noRollbackFor:不回滚

设置出现哪些异常不进行回滚

四、基于xml声明式管理

五、完全注解方式(一般用springboot)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值