Spring 事务传播,不同 Propagation 枚举 的效果
官方说明:
事务传播行为类型
说明
PROPAGATION_REQUIRED
如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择(默认)。
PROPAGATION_SUPPORTS
支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY
使用当前的事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW
新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED
以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER
以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED
如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。
自己代码测试:
1 package com.msb.service.impl; 2 3 import com.msb.dao.AccountDao; 4 import com.msb.service.AccountService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 import org.springframework.transaction.annotation.Propagation; 8 import org.springframework.transaction.annotation.Transactional; 9 10 /** 11 * @Auther: zhangxp 12 * @Date: 2024/7/12 2024 13 * @Description: com.msb.service.impl 14 * @version:1.0 15 */ 16 @Service 17 public class AccountServiceImpl implements AccountService { 18 19 @Autowired 20 private AccountDao accountDao; 21 22 @Override 23 @Transactional(propagation = Propagation.MANDATORY) 24 public int transMoney(int from, int to, int money) { 25 26 accountDao.transMoney(from, -money); 27 //int i = 1/0; 28 accountDao.transMoney(to, money); 29 30 return 2; 31 } 32 }
1 package com.msb.dao.impl; 2 3 import com.msb.dao.AccountDao; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.jdbc.core.JdbcTemplate; 6 import org.springframework.stereotype.Component; 7 import org.springframework.transaction.annotation.Propagation; 8 import org.springframework.transaction.annotation.Transactional; 9 10 /** 11 * @Auther: zhangxp 12 * @Date: 2024/7/12 2024 13 * @Description: com.msb.dao.impl 14 * @version:1.0 15 */ 16 @Component 17 public class AccountDaoImpl implements AccountDao { 18 19 @Autowired 20 private JdbcTemplate jdbcTemplate; 21 22 @Transactional(propagation = Propagation.SUPPORTS) 23 @Override 24 public int transMoney(int id, int money) { 25 String sql = "update account set money = money +? where id =?"; 26 jdbcTemplate.update(sql, money, id); 27 //int i = 1/0; 28 sql = "update account set money = money + 1 where id =?"; 29 return jdbcTemplate.update(sql, id); 30 } 31 }
通过 除0 异常来测试 内层和外层 事务是否有效。
测试结果:
总结:用到事务,就是想要么都操作成功,要么都失败, 就用 propagation 的默认形式 required 的,就是我们想要实现的事务效果。
posted on 2024-07-12 23:54 IT_xiaozhang 阅读(10) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义