在这些情况下,帮助决定何时使用 DTO 以及何时使用 Entity 的一般想法是什么?
我喜欢阅读传递实体的代码:
但是有人认为映射到实体的 DTO 更安全,因为它是一个合约,实体可以更改为任何形式,而 DTO 将保持不变。比如像实体有一个字段名,DTO也有一个字段名。稍后,如果需求发生变化,数据库表发生变化,实体也会发生变化,将 name 更改为 firstName 和 lastName。但是 DTO 仍然会有一个字段名称,即 firstName + lastName。
所以这里是使用 DTO 的优点列表:
我能想到的 DTO 的缺点是:
请分享你的想法..
谢谢 !
以下是来自不同地方的一些报价
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!
最佳答案
临 DTO:
1. UI 大多数时候需要某些属性,这些属性仅用于传递描述 UI 状态的参数。因此,该状态不需要持久化,也不需要在实体上使用。
2. 业务逻辑应该在实体内部或实体的辅助类中。您不应与 UI/Presentation Layer 或调用它的客户端共享它。
3. 实体的变化有时不需要 DTO 的变化,反之亦然。
4. 更容易在 UI 服务中对 DTO 执行系统级验证,从而在不应该的情况下停止对业务服务的调用。
5. 当 UI 端接收 DTO 而不是填充来自 UI 的数据的实体时,您可以自由实现/使用其他验证框架。
6. UI/Presentation 层松耦合。
以下是使用 DTO 时的示例流程:
UI --> MVC --> 使用 UI 服务的系统验证 --> 业务代表 --> 业务服务 --> 持久化。
关于jsf - JPA 实体和/vs DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5216633/