jsf - JPA 实体和/vs DTO

标签 jsf architecture jpa dto

在这些情况下,帮助决定何时使用 DTO 以及何时使用 Entity 的一般想法是什么?

  • UI/服务器端 java 调用服务。它应该获取/发送实体还是 DTO?
  • 调用服务的 Web 服务。服务应该接受实体还是 DTO?

  • 我喜欢阅读传递实体的代码:
  • 更容易传递,无需映射到 DTO
  • 不需要额外的类(class)
  • 与其他实体的关系已经定义,因此不需要将相关的 DTO 合并为一个 DTO
  • 只是 POJO

  • 但是有人认为映射到实体的 DTO 更安全,因为它是一个合约,实体可以更改为任何形式,而 DTO 将保持不变。比如像实体有一个字段名,DTO也有一个字段名。稍后,如果需求发生变化,数据库表发生变化,实体也会发生变化,将 name 更改为 firstName 和 lastName。但是 DTO 仍然会有一个字段名称,即 firstName + lastName。

    所以这里是使用 DTO 的优点列表:
  • 从接受 DTO 的代码的角度来看,向后兼容

  • 我能想到的 DTO 的缺点是:
  • 必须定义 DTO 类和映射(可能使用推土机)
  • 程序员必须分析何时使用 DTO 和实体,我的意思是为每个方法传递 DTO 是一团糟
  • 实体到 DTO 的转换开销,反之亦然
  • 我仍然不确定如何映射它们的一对多关系。在 JPA 中我们可以懒惰地初始化它,但是当传入 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/

    相关文章:

    javascript - Primefaces 4.0 尝试调用错误的 tabChange 事件处理程序(TabView 内的 AccordionPanel)

    java - 如何将表行绑定(bind)到 jsf 中的编辑按钮?

    architecture - 滥用领域驱动设计

    java - 是否可以持久化对象的类?

    JSF 为 h :selectOneMenu (if nothing selected) 自定义验证消息

    java - 如何强制 primefaces 数据表中的文本填充整列

    c# - .NET 架构设计问题

    wpf - 架构:针对 LOB 金融应用程序组合的 WPF 与基于 Web 的对比

    hibernate - JPA 中的条件查询

    java - 有没有办法在 Play! 中使用 MyBatis?框架?