Search code examples
springrestweb-servicesspring-mvcspring-restcontroller

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);  
}

So for this userProfileResponse.setId(??) how can I set the ID value? can I directly do like this userProfileResponse.setId(userProfileResponse.getId());

Or I can Pass one more request body like this

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

Thanks in advance.


Solution

  • You can call createUserProfileData method and return the id of the newly inserted object from it.

    In createUserProfileData method, you can call saveAndFlush method of the repository which will save the userProfile Object.

    This will return the id of the newly inserted object.

    Finally your code will look like below:

    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);  
    }