代码之家  ›  专栏  ›  技术社区  ›  rellocs wood

如何在@Transactional方法中立即执行save操作

  •  0
  • rellocs wood  · 技术社区  · 7 年前

    @Transactional
    public void doSthing(){
         // save an enetity to db
        SomeClass entityA = new entityA();
        mapper.save(entityA);
        // I got null here!
        Integer id = entityA.getId();
        anotherEntity.setVal(id);
        otherMapper.upate(anotherEntity)
    
    }
    

    null 那时,如果我把 @Transactional 它可以工作,但我希望在tansaction中有两个操作,这意味着我需要弹簧回滚 doSthing() 任何操作的方法都失败。

    2 回复  |  直到 7 年前
        1
  •  2
  •   NiVeR    7 年前

    默认情况下,使用 @Transactional RuntimeException . 因此,您可以通过在某些条件下抛出一些运行时异常来实现回滚。

    如果要回滚 任何

    @Transactional(rollbackFor=Exception.class)
    

    但是@Delinum在评论中所说的一般都是正确的,也就是说,如果在dao/存储库上调用save,它应该分配一个 @Id 添加到要保存的值对象,使其成为实体。

        2
  •  1
  •   Selindek    7 年前

    mapper.save(entityA);
    // I got null here!
    Integer id = entityA.getId();
    

    使用此选项:

    Integer id = mapper.save(entityA).getId();