Data Transfer Object (DTO)
● contains data that should be transferred between application layers (but not between application and DB)
● is used as a replacement for Entity when not all Entity Properties need to be sent
Just like Entity, Command Class should only have
● Properties that are equivalent to Table Columns
● Setters and getters for setting and reading these Properties
● Optional Constructor for settings all of these properties at once
Command Class should not have any logic (just pure data to transfer over layers/network).
It also shouldn't contain any methods for converting between Command and Entity Objects.
These methods should be implemented inside Converter Object.
For example, if Table has 100 Columns, then corresponding Entity will have 100 Properties.
But if we need to display only 10 Properties on our interface, these can be encapsulated inside the Command Object.
Now our backend can send Command Object with only 10 Properties to our front end (instead of sending Entity with 100
Properties).
Command (DTO) serves similar purpose to Entity (DO)
● Command (DTO) is used when beck-end wants to send/retrieve data to front-end
● Entity (DO) is used when beck-end wants to send/retrieve data to DB
If your Entity Object is small enough and if it doesn't contain any sensitive data, it can be sent directly to the front-end.
In that case you wouldn't need neither Converter (DCO) nor Command (DTO).
The best way to understand difference between DTO and Entity is to create DTO that contains data for multiple Entities.
Service will then extract data from DTO in order to create distinct Entities that can be stored into DB.
For instance HTML Form might be used to enter both Author and Book data.
Inside Controller such HTTP Request is converted into DTO and forwarded to Service.
In order to save Author and Book as separate Entities Service must extract relevant data from DTO.
DTO can contain data for one or more Entities which are used to create those Entities.
This means that DTO should be converted into Entities.
Conversion is usually done through Mapper Class that maps DTO Properties into Entity Properties with the same name.
Properties that are missing in DTO but exist in Entity remain empty in Entity.
DTO conversion into Entities