@Entity
public class Person{
private String id;
private String name;
private Integer age;
}
There I want to return all the fields to the client, so is there any need to create dto class? what is best practice in such situations?
CodePudding user response:
DTOs help when the domain model is composed of many different objects and the presentation model needs all their data at once, or they can even reduce roundtrip between client and server.
With DTOs, we can build different views from our domain models, allowing us to create other representations of the same domain but optimizing them to the clients' needs without affecting our domain design. Such flexibility is a powerful tool to solve complex problems.
CodePudding user response:
the main reason is because you don’t want to break your API clients when you add, remove or rename a field from the application domain model.
Below a few of benefits of using DTO:
DTOs can be tailored to your needs and they are great when exposing only a set of attributes of your persistence entities. You won't need annotations such as @XmlTransient and @JsonIgnore to avoid the serialization of some attributes.
By using DTOs, you will avoid a hell of annotations in your persistence entities, that is, your persistence entities won't be bloated with non persistence related annotations.
You will have full control over the attributes you are receiving when creating or updating a resource.
You can check this stackoverflow answer for more detail https://stackoverflow.com/a/36175349/3143009