1

For example, I need to update an EntityA. As I am working with DTO's, user needs to transfer DTO for update in Controller. In service layer I extract Entity and update it with DTO fields, then - save it again.

Pretty simple and basic stuff, but what If I want to return an updated object? I can't return the DTO user sent to me ( it has NULL in some fields as the same DTO is used for both update and creation ). What should I do in that kind of situation? Create second DTO just to return an updated value? Is it common to return void in update?

2 Answers2

1

You shouldn't expose Entities on REST APIs in general. Because then you may not be able to change the Entities .

The only exception is when the REST API is only used by the UI and the UI is part of the whole application.

Back to your question: You must return a DTO that is updated from the saved entity.

To read DTOs you don't need to map them you can directly fetch DTOs either with the JPA constructor expression or with Spring Data JPA various projection options.

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
  • What if DTO object can't be created purely from underlying domain object? As in one might have additional variable, that holds logic, that is required for DTO creation. e.g. in this article https://www.baeldung.com/java-dto-pattern user provides roles to create DTO with flat structure, but what what if user and roles are initially separate and one does wish to return them as a single DTO? How should it be handled then? – Eugene May 14 '22 at 05:07
  • If it's on the database you can simply create a query – Simon Martinelli May 14 '22 at 07:22
0

As said in this post Should a RESTful 'PUT' operation return something

HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)

This means, you are not forced to return the updated object, it's up to you, I usually return the body of my PUT, for one simple reason, the user should always have a representation of the real situation present on db.

Check out this post too What REST PUT/POST/DELETE calls should return by a convention?

To answer to the other question, no you don't need to create a second DTO, you can map the entity values to the one the user sent to you or you can do what Simon said.

xTheDoctah
  • 276
  • 1
  • 11