I have started a Spring Rest project as a beginner. Most of my entities have more than 15-20 attributes and not all attributes are required on the UI layer.
I am considering using DTO for the following reasons:
I am considering using DTO to merge multiple entities together, hide/show certain information for certain UI based on the roles, but I have to "split/copy" the DTO information back to different entities when I need to persist the details.
Staff - Able to view the performance appraisal and comments by the next level manager. Manager - Able to enter comments for the performance appraisal, and indicate the pay increment for the staff (This is not shown in the staff's UI), but not able to view the staff's current pay. HR - Able to view all the details for all UI.
I would like to find out if there is a better way to handle such concerns or am I heading the right direction for my project?
Ref: http://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
It's better to use the DTO to have a clean architecture, with DTO, when you modify the Table, nothing will be changed for the FrontEnd.
BUT it's better to use it carefully.
Good luck.
I always use DTOs to decouple my views from my JPA entities. In addition to the 3 reasons you list I can add the following.
@JSONCreator
you can have immutable DTO, which can have some advantages - although most times DTOs are not used in a multi threaded context, and therefore not needed.In My projects I always use Lombok to generate access method, which means that DTOs usually only contain the data field (sometimes input DTO has validator or utility method). This makes them super easy to create/modify, and easy to distinguish from classes that contain logic. Creating the DTOs takes no time compared to writing the business logic, so there is very little cost of having this decoupling, and I honestly believe it makes it easier to read the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With