Is it ok to return a real entity when working with DTO's

Viewed 353

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 Answers

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.

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.

Related