JPA Entities and/vs DTOs

后端 未结 2 1888
孤城傲影
孤城傲影 2021-02-02 10:37

What is the general idea to help deciding when to use DTO and when to use Entity in these cases ?

  1. UI / server side java calling the services. Should it get / send
2条回答
  •  无人共我
    2021-02-02 11:25

    Pro DTO: 1. UI most of the times require certain properties which are only for passing arguments depicting the UI state. That state is not required to be persisted hence, not required to be used on the entities.
    2. Business logic should be inside entities or in helper classes for entites. You should not share that with the UI/Presentation Layer or with Client calling it.
    3. Change in entities sometimes does not require a change in DTOs and vice versa.
    4. Easier to perform System Level validations on DTOs in UI Services hence stopping the call to the Business Services when it should not.
    5. You can implement/use other validation frameworks freely when UI side is receiving a DTO rather than entity filled with the data coming from the UI.
    6. UI/Presentation layer is loosely coupled.

    Here is a sample flow when DTOs are used:
    UI --> MVC --> System Validations using UI Services --> Business Delegate --> Business Services --> Persist.

提交回复
热议问题