V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
fogsky
V2EX  ›  问与答

spring 中事务不起作用

  •  
  •   fogsky · 2021-01-03 21:14:59 +08:00 · 1108 次点击
    这是一个创建于 1207 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在学习 spring 事务。看完文档写了个 demo,发现事务没起作用。 具体问题是这样: 1 、 @Transactional ServiceA method 1 插入数据,@Transactional ServiceB method 2 中只抛出空指针异 常,结果发现数据库中 method1 插入数据提交了。 2 、method 1 中加入抛出空指针代码,并单独在 controller 中调用,则在数据库中未发现新数据插入。 框架使用的 spring boot+mybatis 。 代码 Controller:

    @RequestMapping("/transaction")

    public String transactionTest() {
    	
    	  Book book=new Book(); 
    	  book.setName("发"); 
    	  book.setAuthor("fage");
    	  book.setPrice(102); 
    	  bookService.saveOrUpdate(book);
    	  serviceForTest.transactionTest(); 
    	return "home";
    }
    

    ServiceA:

    @Transactional(propagation=Propagation.REQUIRED)

    public int saveOrUpdate(Book b) {
    
    	int i;
    	// TODO Auto-generated method stub
    	if(b.getId()==null) {
    
    		i=bookMapper.insertBook(b);
    

    // String a = null; // a.indexOf('c'); return i;

            }
    
    	return bookMapper.updateById(b);
    	
    }
    

    ServiceB:

    @Transactional(propagation=Propagation.REQUIRED)

    public void transactionTest() {
    
    	// TODO Auto-generated method stub
    		String a = null;
            a.indexOf('c');
    
    }
    
    7 条回复    2021-01-04 21:51:00 +08:00
    340244120w
        1
    340244120w  
       2021-01-03 21:23:54 +08:00 via iPhone
    不是没生效,只是没用对 。把 controller 的调用的多个方法 封装成一个事务就好了。
    fogsky
        2
    fogsky  
    OP
       2021-01-03 21:33:46 +08:00
    @340244120w 封装成一个事务指的是?我只配置了一个 datasource,自动配置应该也是只配置了一个事务管理器。
    micean
        3
    micean  
       2021-01-03 21:48:01 +08:00
    建议先玩 jdbc 的事务,再回头看 spring 的事务
    340244120w
        4
    340244120w  
       2021-01-03 22:29:30 +08:00 via iPhone   ❤️ 1
    @fogsky 简单的说 一个注解默认对应一个单独的事务。而只有处在同一事务下的方法,才能统一回滚。而你的写法是两个事务了。
    至于前面说的默认,可以看下 spring 事务传播。
    fogsky
        5
    fogsky  
    OP
       2021-01-03 23:26:44 +08:00
    @340244120w 以为 propagation 设置为 required method2 就会加入 method 1 的事务。非常感谢解答。
    w292614191
        6
    w292614191  
       2021-01-04 09:11:27 +08:00
    这是两个独立的事务了,如果你在 A 中调 B,B 异常了 A 回滚。
    如果你在 Controller 调 A,B,她们并没有关系。
    fogsky
        7
    fogsky  
    OP
       2021-01-04 21:51:00 +08:00
    @w292614191 恩,懂了,需要方法外部有事务存在。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3774 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:16 · PVG 12:16 · LAX 21:16 · JFK 00:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.