• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

IT_xiaozhang

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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  阅读(20)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3