What is the general idea to help deciding when to use DTO and when to use Entity in these cases ?
- UI / server side java calling the services. Should it get / send entities or DTOs ?
- Web service calling the services. Should the services accept entities or DTOs ?
I like reading the code that pass entities around :
- simpler to pass around, no need to map to DTOs
- dont need extra classes
- relations to other entities are already defined, so dont need combine related DTOs into one DTO
- just POJOs
But there are arguments about DTO that maps to an entity is safer, because it's a contract, and the entity can change to whatever form, and the DTO will stay the same. For example, like the entity has a field name, and the DTO also has a field name. Later on, if the requirement changes, the database table changes, the entity can change also, changing name into firstName and lastName. But the DTO will still have a field name, which is firstName + lastName.
So here's the list of the pros of using DTOs :
- backward compatible from the viewpoint of the code that accepts the DTOs
The cons of DTO i can think of is :
- have to define the DTO classes and the mapping (perhaps using dozer)
- the programmers would have to analyze when to use DTO and entity, i mean passing DTO for every methods is a mess
- overhead of conversion of entities to DTOs and vice versa
- I'm still unsure about the one-to-many relationship on how to map them. In JPA we can lazy initialize this, but when passing in DTO, should i initialize this or not. Shortly, DTOs cant have lazy initialized proxies, only contains values.
Please share you thoughts ..
Thank you !
Here are some quotes from different places
pro dto :
Reuse of the entity class as a DTO seems messy. The public API of the class (including annotations on public methods) no longer clearly defines the purpose of the contract it is presenting. The class will end up with methods that are only relevant when the class is being used as a DTO and some methods that will only be relevant when the class is being used as an entity. Concerns will not be cleanly separated and things will be more tightly coupled. To me that is a more important design consideration then trying to save on the number of class files created.
pro entity :
Absolutely NOT!!!
JPA entities are mapped to a database, but they are not 'tied' to a database. If the database changes, you change the mappings, not the objects. The objects stay the same. That's the whole point!