JPA Entities and/vs DTOs

后端 未结 2 1883
孤城傲影
孤城傲影 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.

    0 讨论(0)
  • 2021-02-02 11:29

    I would go for the DTO option for the following reasons:

    • The service interface should be independant of the database, a change in one should not always require a change in the other.
    • You are making an assumption that your services will always be called by a Java client
    • Using lazy loading when the object is on the otherside of a web service call does not work well.
    0 讨论(0)
提交回复
热议问题