@transactional保存为springboot JPA

时间:2019-10-05 13:54:37

标签: java spring-boot jpa spring-data-jpa

我需要实现

的实体save方法
  • 将实体保存到数据库
  • 返回附属实体
  • 设置entity.id以请求正文
  • 拨打外部服务电话
  • 使用响应中的相应字段更新实体字段“ externalId”
  • 将实体转移到数据库

如果外部服务响应错误,则回滚事务。

我试图做的事

    @Transactional
    public MyEntity save(MyEntity model) {
        // more complex logic here: save if not exists
        // omitted for brevity
        var savedEntity = recipientRepository.save(entity); 
        var createdExternalEntity = restClient.createExternalEntity(
                savedEntity); // assume savedEntity has savedEntity.id set at this point

        // update field for a newly created 
        savedEntity.setExternalId(createdExternalEntity.getId());

        return savedEntity;
    }

问题: savedEntity.setExternalId(createdExternalEntity.getId());似乎无效

我什至没有尝试模拟restClient.createExternalEntity并抛出异常以查看事务是否真的回滚

1 个答案:

答案 0 :(得分:0)

这是我的错。 savedEntityattached @Transactional方法中对其字段的任何更改都会反映到数据库中。