Search code examples
javaspringresthttpdto

Spring MVC - returning DTO in response body for POST Request?


I have the following controller POST method that creates a new meeting.

@PostMapping("/meetings")
ResponseEntity<Object> createMeeting(@RequestBody MeetingDTO meetingDTO) {

    meetingService.createMeeting(meetingDTO);
    return ResponseEntity.ok("created");
}

This is the service logic where I update my Meeting database entity using the MeetingDTO:

    public void createMeeting(MeetingDTO meetingDTO){

    Organiser organiser = personRepository.findById(meetingDTO.getPersonId())
            .orElseThrow(() -> new RuntimeException("No Person with Id "
                    + meetingDTO.getPersonId()));

    Meeting meeting = new Meeting();
    meeting.setDate(meetingDTO.getDate());
    meeting.setTime(meetingDTO.getTime());
    meeting.setOrganiser(organiser);

    meetingRepository.save(meeting);
}

I am using MeetingDTO as the request body in my POST as I do not want to expose certain other fields within Meeting Entity.

Is this a correct use of the DTO pattern? Should I be returning the DTO again in the POST response in the response body?


Solution

  • This is correct usage of DTO and Entity. Domain model shouldn't be exposed to outside world. enter image description here Here is good article on this topic: Understanding Spring Web Application Architecture: The Classic Way