【问题标题】:JpaRepository save not returning the attributes of nested objects updated by idJpaRepository 保存不返回由 id 更新的嵌套对象的属性
【发布时间】:2022-08-24 21:00:23
【问题描述】:

我有一个正在更新的用户提出了补丁请求,并且允许客户端发送 带有图像 ID 的 json 请求,因此我可以将 if 分配给用户

{\"image\": {\"id\": 3}}

而完整的图像对象是这样的

 \"image\": {
    \"id\": 3,
    \"fileUrl\": \"/uploads/identity.jpg\",
    \"fileUrlType\": \"RELATIVE\"
}

当我将 id 分配给新的 Image Entity 并将其设置给我的用户然后调用 repository.save(update User) 时,它会正确保存到具有所有属性的数据库中。

问题是 save 方法的返回是返回一个用户只有一个 id 属性的图像(其他属性设置为 null)

PS:当我稍后尝试从另一个请求中获取用户时,我发现它具有它需要的所有图像属性

有没有办法让存储库?save(updatedUser) 返回用户。图像及其所有属性?

我试着打电话保存并刷新代替节省但它没有用,我也尝试在保存后直接调用 getById(user.id) 也没有用

这是我的服务代码

    public User patchUser(User user, FullUserDto userDto) {
    userMapper.updateUserFromDto(userDto, user);
    return this.userRepository.save(user);
}
  • 你能发布你的实体定义吗?

标签: java spring-boot hibernate jpa


【解决方案1】:

保存后调用 entityManager.refresh(user) 解决的问题

【讨论】:

    【解决方案2】:

    我发现我需要改变两件事:

    1. 使用saveAndFlush(user) 而不是save(user)
    2. 调用 saveAndFlush 后调用 entityManager.refresh(user)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多