Spring 当我们有两个对象时,REST ResponseEntity 如何 return 响应

Spring REST ResponseEntity how to return response when we have two objects

1. For example UserProfile which has 3 properties name,dob, age 2. And 2nd class let's say UserProfileResponse which has only "id"

public ResponseEntity<UserProfileResponse> createUserProfile(@RequestBody UserProfile userProfile)
{
      UserProfileResponse userProfileResponse = new UserProfileResponse();
      userProfileResponse.setId(??)  // How do I set ID?
      **createUserProfileData(userProfile)  /// This is used to create DB record** 
      return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);  
}

那么对于这个 userProfileResponse.setId(??) 我该如何设置 ID 值呢? 我可以直接这样做吗userProfileResponse.setId(userProfileResponse.getId());

或者我可以像这样再传递一个请求体

ResponseEntity<UserProfileResponse> createUserProfile(@RequestBody UserProfile userProfile, @RequestBody ID)

提前致谢。

你可以调用createUserProfileData方法和return新插入对象的id。

createUserProfileData 方法中,您可以调用存储库的 saveAndFlush 方法来保存 userProfile 对象。

这将 return 新插入对象的 ID。

最后您的代码将如下所示:

public ResponseEntity<UserProfileResponse> createUserProfile(@RequestBody UserProfile userProfile)
{
      UserProfileResponse userProfileResponse = new UserProfileResponse();
      int id = createUserProfileData(userProfile)
      userProfileResponse.setId(id) 
      return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);  
}

如果您想从 RequestBody UserProfile 中获取一个不包含它的值actually.Sorry,那是不可能的。

而且我们一次只能接收一个requestBody,所以我们需要使用其他方式来收集info.There还有一些其他的解决方案:

  • 使用@PathVariable 从 url
  • 获取 ID
  • 使用@RequestParam从requestParam获取Id
  • 在您的用户配置文件中添加一个名为 Id 的新字段
  • 使用其他方式获取您的 Id,这取决于您如何持久化或生成 Id。

对于你的情况,我不确定你要用这个 id 做什么。

如果"createUserProfileData"方法意味着您需要先提供一个id才能持久化。

嗯,我不知道你是什么数据库,什么框架using.As我知道,大多数框架和数据库都有生成id的能力automatically.But如果你一定要生成id由你自己,我推荐你 UUID。

如果"createUserProfileData"方法是按字面意义将UserProfile保存到数据库中,而id是由数据库本身生成的,那么你只需这样做并将代表你刚刚保存的记录的Id放入UserProfileResponse。

至于如何获取代表你刚刚保存的记录的id?这取决于你使用的框架和具体代码的编写方式。