DEV Community

Wagner Negrão 👨‍🔧
Wagner Negrão 👨‍🔧

Posted on

Difference between Entity and DTO

This post seeks to present entity and DTO in a low complexity aiming at the beginner developer.

Entities are classes that have a relation intrinsic to the business, for example, a class that maps a table of databases so has Id and other fields.

{
private Long id;
private String firstName;
private String lastName;
private String email
}

Enter fullscreen mode Exit fullscreen mode

Value Object or Data Transfer Object are classes that aim to map fields from an entity, add functions or remove fields. This basically consists of transitioning fields within the project.

{
private String firstName;
private String lastName;
private String email
}

Enter fullscreen mode Exit fullscreen mode

The Dto it have some characteristics, like the principle of immutable, and also serve like filter to fields received in a request body for example a field of email that can do a regex before of we pass this field to an entity.

The relationship between entity and DTO may be as follows.

Diagram containing the entity flow, DTO and Response

This mode aims to be able to abstract certain fields for those who will receive the information.

Example:

Above we have the FirstName and LastName fields inside the entity, we can return a field called FullName that concatena this fields and returns a single field, soon we would have something like.

{
private String fullName;
private String email;
}
Enter fullscreen mode Exit fullscreen mode

Now we have the opposite that it will be external information for the entity.

Diagram containing the request flow, DTO and Entity

With the information we are receiving as a Request Body we can make validations such as to check the email standard will be accepted or the amount of characteristics. This enables the maintenance of the integrity of the data that will be transacted within the application, protecting the core of the application.

Top comments (0)