【Spring进阶系列丨最终篇】一文详解Spring中的事务控制

embedded/2024/10/18 14:26:40/

0、说明

本篇文章是【Spring进阶系列】专栏的最后一篇文章,至此,我们对Spring的学习就告一段落,接下来我会持续更新【Spring+SpringMVC+MyBatis整合】专栏,欢迎免费订阅!

文章目录

    • 0、说明
  • 一、Spring事务控制
    • 1、事务的环境准备
      • 1.1、导入依赖
      • 1.2、添加AOP的约束
      • 1.3、数据库准备
      • 1.4、定义Bean
      • 1.5、主配置文件定义
      • 1.6、测试
    • 2、基于xml的声明式事务
      • 2.1、配置事务管理器
      • 2.2、配置事务的通知
      • 2.3、配置AOP
      • 2.4、配置事务的属性
    • 3、基于注解的声明式事务
      • 3.1、配置事务管理器
      • 3.2、在业务类添加注解
      • 3.3、配置JdbcTemplate模板
      • 3.4、在Dao类添加注解
      • 3.5、配置类中扫描包
      • 3.6、开启spring对注解事务的支持
      • 3.7、在业务层@Transactional注解
      • 3.8、测试

在这里插入图片描述

一、Spring事务控制

在这里插入图片描述

  • 事务需要放在业务层(service)
  • Spring的事务是基于AOP的
  • Spring的事务控制有两种:编程式事务【了解】和声明式事务【重点】
  • 声明式事务分为:基于xml配置和基于注解配置

1、事务的环境准备

1.1、导入依赖

<dependencies><!-- 导入Spring的jar包--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.1.RELEASE</version></dependency><!-- 添加对AOP的支持  --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.4</version></dependency><!-- 事务的jar包    --><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.1.RELEASE</version></dependency><!-- 数据库驱动  --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><!-- 操作数据库的支持	--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.1.RELEASE</version></dependency><!--  单元测试框架  --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
</dependencies>

1.2、添加AOP的约束

<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/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttps://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

1.3、数据库准备

create database bank;use bank;create table t_account(id int primary key auto_increment,name varchar(30),balance int
);insert into t_account(name,balance) values('段康家',2000);
insert into t_account(name,balance) values('彭依凝',2000);

1.4、定义Bean

java">// 定义实体
public class Account {private Integer id;private String name;private Integer balance;
}
java">// 业务接口
public interface AccountService {public void transfer(Integer srcId,Integer destId,Integer money);}
public class AccountServiceImpl implements AccountService {@Overridepublic void transfer(Integer srcId, Integer destId, Integer money) {// 源账号Account srcAccount = accountDao.selectById(srcId);Integer srcBalance = srcAccount.getBalance();srcAccount.setBalance(srcBalance - money);accountDao.updateById(srcAccount);// 目标账号Account destAccount = accountDao.selectById(destId);Integer destBalance = destAccount.getBalance();destAccount.setBalance(destBalance + money);accountDao.updateById(destAccount);}
}
java">// dao接口
public interface AccountDao {public Account selectById(Integer id);public void updateById(Account account);}
// dao实现类
public class AccountDaoImpl implements AccountDao {@Overridepublic Account selectById(Integer id) {String sql = "select id,name,balance from t_account where id = ?";List<Account> accounts = getJdbcTemplate().query(sql,new BeanPropertyRowMapper<Account>(Account.class),id);return accounts.get(0);}@Overridepublic void updateById(Account account) {String sql = "update t_account set balance = ? where id = ?";getJdbcTemplate().update(sql,account.getBalance(),account.getId());}
}

1.5、主配置文件定义

<beans> <!-- 配置Dao层--><bean id="accountDao" class="cn.bdqn.dao.impl.AccountDaoImpl"><property name="dataSource" ref=""/></bean><!-- 配置业务层--><bean id="accountService" class="cn.bdqn.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!-- 配置数据源  --><bean id="dataSource" 																class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql:///bank"></property><property name="username" value="root"></property><property name="password" value="root"></property></bean></beans>

1.6、测试

java">@Test
public void testTransfer() throws Exception{ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");AccountService accountService = (AccountService) ac.getBean("accountService");accountService.transfer(1,2,100);
}

2、基于xml的声明式事务

2.1、配置事务管理器

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

2.2、配置事务的通知

 <!-- 2、配置事务的通知  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"/>

2.3、配置AOP

​ 重点是配置切入点表达式及事务通知和切入点表达式的关系

<!-- 3、开启配置AOP 配置切入点表达式及事务通知和切入点表达式的关系-->
<aop:config><aop:pointcut id="pt" expression="execution(* cn.bdqn.service.impl.*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>

2.4、配置事务的属性

​ 注意:事务的属性在tx:advice标签的内部。

isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。

propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。

read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。

timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。

rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。

no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。

<!-- 2、配置事务的通知  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"><!-- 配置事务的属性--><tx:attributes><tx:method name="transfer" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/></tx:attributes>
</tx:advice>

3、基于注解的声明式事务

3.1、配置事务管理器

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

3.2、在业务类添加注解

java">@Service("accountService")
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;

3.3、配置JdbcTemplate模板

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/>
</bean>

3.4、在Dao类添加注解

java">@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {@Autowiredprivate JdbcTemplate jdbcTemplate;
}

3.5、配置类中扫描包

java"><context:component-scan base-package="cn.bdqn"/>

spring_333">3.6、开启spring对注解事务的支持

<tx:annotation-driven transaction-manager="transactionManager"/>

3.7、在业务层@Transactional注解

java">@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;
}

3.8、测试

java">@Test
public void testTransfer() throws Exception{ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");AccountService accountService = (AccountService) ac.getBean("accountService");accountService.transfer(1,2,100);
}

在这里插入图片描述


http://www.ppmy.cn/embedded/10089.html

相关文章

Python网络爬虫项目开发实战:如何处理并发下载

注意&#xff1a;本文的下载教程&#xff0c;与以下文章的思路有相同点&#xff0c;也有不同点&#xff0c;最终目标只是让读者从多维度去熟练掌握本知识点。 下载教程&#xff1a;Python网络爬虫项目开发实战_并发下载_编程案例解析实例详解课程教程.pdf 在Python网络爬虫项目…

Mysql 在Windows Server系统下修改数据文件存储路径遇到的坑

因项目需要搭建一个Mysql数据库&#xff0c;为了方便日常运维操作开始选择了Windows Server 2012R2(已有的虚拟机)&#xff0c;考滤到要300G空间&#xff0c;原来的盘空间不够了,就是给虚拟机加了磁盘&#xff0c;Mysql 8.0.26社区版安装路径没得选择&#xff0c;默认就装在C&a…

STM32 堆栈内存以及变量存储分布

STM32的程序存储器、数据存储器、寄存器和输入输出端口被组织在同一个4GB的线性地址空间内, 地址范围为0x0000 0000至0xFFFF FFFF。其中FLASH为ROM类型&#xff0c;储存的数据掉电不易失&#xff1b;RAM中存储的数据掉电易失。以STM32F103系列为例&#xff0c;最多有512KB的FLA…

UML类图

类图(Class diagram)是显示了模型的静态结构&#xff0c;特别是模型中存在的类、类的内部结构以及它们与其他类的关系等。类图不显示暂时性的信息。类图是面向对象建模的主要组成部分。 类使用包含类名、属性(field) 和方法(method) 且带有分割线的矩形来表示属性/方法名称前加…

前端框架技术调研

目前程序员使用前端框架最多的是哪一个&#xff1f;

端口被占用的解决方案汇总

端口被占用的解决方案汇总 【一】windows系统端口被占用【二】Linux系统端口被占用【三】Linux的ps命令查找&#xff08;1&#xff09;ps命令常用的方式有三种&#xff08;2&#xff09;ps -ef |grep 8080 【一】windows系统端口被占用 &#xff08;1&#xff09;键盘上按住Wi…

Valentina Studio Pro for Mac:强大的数据库管理工具

Valentina Studio Pro for Mac是一款功能全面、操作高效的数据库管理工具&#xff0c;专为Mac用户设计&#xff0c;旨在帮助用户轻松管理各种类型的数据库。 Valentina Studio Pro for Mac v13.10激活版下载 该软件拥有直观的用户界面&#xff0c;使得数据库管理变得简单直观。…

深度剖析图像处理—边缘检测

什么是边缘检测 边缘检测(Edge Detection)就是提取图像中的边缘点(Edge Point)。边缘点是与周围像素相比灰度值有阶跃变化或屋顶状变化的像素。边缘常存在于目标与背景之间、目标与目标之间、目标与其影子之间。 ​ 在图像处理和图像分析中&#xff0c;经常要用到边缘(Edge)、边…