Difference between Entity and DTO
Asked Answered
S

4

97

What is the difference between a DTO and an Entity? In details these are my questions:

  1. What fields should the DTOs have? For example my entity classes are:

    @Entity
    public class MyFirstEntity implements Serializable {
    
        @Id @GeneratedValue
        private Long id;
    
        private String stringData;
    
        @OneToOne
        private MySecondEntity mySecondEntity;
    
        @OneToMany
        private List<MySecondEntity> mySecondEntitesList;
    
    }
    
    @Entity
    public class MySecondEntity implements Serializable {
    
        @Id @GeneratedValue
        private Long id;
    
        private Integer integerData;
    
        @ManyToOne
        private MyFirstEntity myFirstEntity;
    
    }
    

There is a one-sided connection (One-to-one) and a two-sided connection (Many-to-one), a simple String and Integer data and of course the ids. What to put from them in the MyFirstDTO and MySecondDTO classes?

  1. If there is an inheritance between the entities, then how should I represent it in the DTOs? For example:

    @Entity
    public class MyFirstEntity extends MySecondEntity {
        ....
    }
    
    @Entity
    public class MyFirstDTO extends MySecondDTO {
        ....
    }
    
  2. How should I use them? For example, I find out this: I'm working on a web project. The user of the webpage wants to register. He/She fills the forms, and sends it to the server. On the server side I create first a DTO, because its fields have the validations. From the DTO I create an Entity and persist it to the database. When there is a request for an entity, I convert the requested entity to DTO, and give it to the user on the client side. Is it a good imagination, or not?

Soke answered 8/9, 2016 at 17:40 Comment(7)
Have you looked at the dozens of other questions related to DTOs on here? Like this one?Immunochemistry
I've read those. I just want to make sure in these conrete examples.Soke
And the page you linked didn't even mention the question I asked.Soke
You mean "what fields should the DTO have"?Immunochemistry
For example. There are no mentions about ids, connections between entities, inheritance. And my last question is specific.Soke
You're supposed to build your DTO the way you need. It's called "Data Transfer Object" so include any data you want to transfer.Immunochemistry
Here is the detail explanation of dto and entity with real life example youtu.be/MKowHmVWqAcCanonize
C
117

Short answer:

  • Entities may be part of a business domain. Thus, they can implement behavior and be applied to different use cases within the domain.

  • DTOs are used only to transfer data from one process or context to another. As such, they are without behavior - except for very basic and usually standardised storage and retrieval functions.

Long answer:

While the term "Data Transfer Object" (DTO) is defined quite unambiguously, the term "Entity" is interpreted differently in various contexts.

The most relevant interpretations of the term "Entity", in my opinion, are the following three:

  1. In the context of entity-relationship- and ORM-frameworks - specifically Enterprise Java and Jpa:
    "An object that represents persistent data maintained in a database."

  2. In the context of "Domain-Driven Design" (by Eric Evans):
    "An object defined primarily by its identity, rather than its attributes."

  3. In the context of "Clean Architecture" (by Robert C. Martin):
    "An object that encapsulates enterprise-wide critical business rules."

The Jee- and Jpa-community sees entities primarily as objects mapped to a database table. This point of view is very close to the definition of a DTO - and that's where much of the confusion probably stems from.

In the context of domain-driven-design, as well as Robert Martins point of view, however, Entities are part of a business domain and thus can and should implement behavior.

Carol answered 21/7, 2018 at 16:42 Comment(6)
Great answer! Thought of adding few more links enterprisecraftsmanship.com/2015/04/13/…Soiree
I have some trouble understanding how DTOs and entities should be implemented. In this blog post R. Martin says that DTOs are data structures. Therefore ORM frameworks don't build business objects but they extract the data the business objects operate on. But how do I implement this distinction correctly? Should I define an EmployeeEntity which contains an EmployeeDTO which was extracted by the ORM? I always thought that my entity class (business object) has to be mapped by the ORM.Necktie
"The Jee- and Jpa-community sees entities primarily as objects mapped to a database table" - Only JEE and JPA? I don't think so. ORM built into .Net is called Entity Framework - so clearly same is happening in C#/.Net world as well.Inadvertent
Just to clearify, business domain here mean anything after service layer to data layer, is this what you mean? Also what do you mean by behavior?Bruis
No, the three-tier-architecture has nothing or very little to do with my statement. "Business domain" is a general term for modeling objects and their behavior from the "real world". If you work for a company, then "business" is more or less the "real world" whose requirements you are trying to implement. The term forms a contrast to the "technical domain", which is about purely technical things. Here is a post with more details and examples: softwareengineering.stackexchange.com/a/314839Carol
As @Inadvertent correctly pointed out, my statement about "Jee and Jpa" was unnecessarily limited to the Java world. I just edited my post to mention ER and ORM-frameworks.Carol
I
64

Difference between DTO & Entity:

Entity is class mapped to table. Dto is class mapped to "view" layer mostly. What needed to store is entity & which needed to 'show' on web page is DTO.

Example : If I want to store employee model as follows : Take employee as an example, I need to store gender either male/female/other. But on JSP I need to show all three values as form 'options' so user can select one.

@Entity
public class Employee{
//annotate with @Id and others

private Long id;
private String name;
private Gender gender; //this is enum viz Male,female
}
//Now extend Dto with employee

public EmployeeDto extends Employee{
Gender[] genders=Gender.values(); //put all gender types in array.
}

while rendering jsp we can give

<select name="gender"> //pointed towards entity gender field.
  <option value="Male">Male</option>
  <option value="Female">Female</option>
  <option value="Other">Other</option>
</select>

then in spring or some other framework whichever selected will be opted as gender in entity.This is made possible because Dto had all three values of gender in it. Similarly, as per situation things follows. As mostly we need most of entity fields on jsp we extend dto by entity.

Imbue answered 8/9, 2016 at 19:3 Comment(3)
-1. DTOs are commonly known as objects passing through the architectural boundaries to transfer data. While they can be used to transfer data to the presentation layer, they are not defined by this specific usage.Uda
right, a DTO can also represent a record in database.Severini
I think you're answer assumes you're implementing Domain Driven Design? Is that right? I think "entities" could be referring to DatabaseEntities from an ORM perspective.Presuppose
P
13

Simple talk:
DTO stands for Data Transfer Object. DTOs are mainly used for transferring data between services (web services, APIs, etc.) which can encompass variety of properties of different entities (with or without their ID). Take this row as an example of a DTO: Consider that a shopping website is going to send its shipping requests to a shipping company by a web-service. Its DTO would be something like this: CustomerFullName, ShippingFee, ShippingAddress. In this example CustomerFullName is combination of properties FirstName + LastName for the Customer entity, and ShippingFee is the result of several processes of destination, tax, etc over some other entities.

On the contrary, Entities are bunch of properties gathered to represent a single entity with a specific ID (e.g., Teacher, Student, Employee, etc.). In other words, DTOs are a bunch of meaningless properties gathered to be sent to the client and a DTO doesn't necessarily have relationship to the other DTOs, while an Entity includes properties of a specific object with meaningful relation to the other entities. In a relational database paradigm, we can look at DTOs as views' row while Entities are tables' row with the primary key. @Shatayu Darbhe also have mentioned this in his/her answer.

However, Model is a combination of these two. A model can contain several related entities plus extra data to handle real-world application/UI problems. Consider a Model named CustomerOrdersModel that contains Customer Entity, List<Order> Entities, and an extra Boolean flag PayWithCredit specifying whether user is going to pay with debit-card or credit-card.

Pegmatite answered 3/1, 2022 at 15:52 Comment(1)
Nice touch on adding the Model definition.Sandler
J
7

"Entities" refer to units of composition of the overall system data. They normally represent business objects like: bank accounts, employees, products, etc. They can be used to persist the state of the system to a database.

"Data transfer objects" are emphemeral collections of data transferred for a very specific purpose. For example, to display a list of products of a specific kind to an end user. You do not want to send all of the data that represents every product entity to the user, but only what is needed for this purpose.

The the Microsoft 2014 MVC documentation explains why you would want to create DTOs from entities. These are some examples of what they suggest that you do to convert entities to DTOs.

  • Remove circular references.
  • Hide particular properties that clients are not supposed to view.
  • Omit some properties in order to reduce payload size.
  • Flatten object graphs that contain nested objects, to make them more convenient for clients.
  • Avoid "over-posting" vulnerabilities. (See Model Validation for a discussion of over-posting.)
  • Decouple your service layer from your database layer.

But it's important to understand that none of these are hard rules that need to be followed. It all depends on what data is best to send your client and what format would be most useful for your client.

What does the client need to do with the data?

  • Will it be edited or just viewed?
  • Do clients care about the order of the int list?
  • Will insertions or deletions of an int need to be made?
  • Will the list need to be rearranged?

Does the client need to know about the 1-1 or 1-many relationships or the fact that there's inheritance? Sending this information may be just adding unnecessary complexity for the client.

These and other questions need to be answered before deciding what data to send the client and how to send it.

Jolynjolynn answered 22/12, 2020 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.