展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

spring5入门(十七):事务管理,注解方式配置

  • 事务管理方式
编程式
声明式
  • 声明式事务操作
public void accountMoney() {
try {
// 第一步 开启事务
// 第二步 进行业务操作
// 业务处理
userDao.reduceMoney();
//模拟异常
int i = 10/0;
// 业务处理
userDao.addMoney();
//第三步 没有发生异常,提交事务
}catch(Exception e) {
// 第四步 出现异常,事务回滚
}
}
  • 声明式事务管理,配置方式
基于注解方式
基于xml配置文件方式
  • 基于注解配置事务管理
# bean.xml中配置事务管理器
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
# 创建名称空间
<?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: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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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>
# 为业务类或方法添加注解
@Transactional
# 注意
如果把这个注解添加类上面,这个类里面所有的方法都添加事务
如果把这个注解添加方法上面,为这个方法添加事务
posted @   DogLeftover  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示