jpa - Spring 数据: when use Projection interfaces and DTO projections?

标签 jpa spring-data spring-data-jpa

我有这种情况:

  • Spring Data JPA: Work with Pageable but with a specific set of fields of the entity

  • 它即将与 Spring Data 合作并使用 @Entity 的一组特定字段

    这两个建议对我来说完全有效:
  • DTO projections
  • Projection interfaces

  • 更多,在 spring-data-examples两者一起出现(我知道是为了示例):
  • CustomerRepository.java

  • 因此:
  • 什么时候强制使用一种,为什么?
  • 是否存在一种性能成本?

  • 备注 Class-based Projections (DTOs)部分内容如下:

    Another way of defining projections is by using value type DTOs (Data Transfer Objects) that hold properties for the fields that are supposed to be retrieved. These DTO types can be used in exactly the same way projection interfaces are used, except that no proxying happens and no nested projections can be applied.



    似乎优点是:except that no proxying happensno nested projections can be applied

    最佳答案

    DTO 方法


  • 简单直接

  • 骗局
  • 这将导致更多代码,因为您必须使用构造函数和 getter/setter 创建 DTO 类(除非您使用 Project Lombok 来避免样板
    DTO 的代码)。
  • 不能应用嵌套投影。

  • 预测


  • 更少的代码,因为它只使用接口(interface)。
  • 可以应用嵌套投影
  • 动态投影允许您编写一种通用存储库方法来返回
    根据客户的需要,实体对象中属性的不同子集。

  • 骗局
  • Spring 在运行时生成代理
  • 查询可以将整个实体对象从数据库返回到 Spring 层,尽管修剪版本(通过投影)从 Spring 层返回到客户端。我不确定这个特定的缺点,希望有人在必要时编辑这个答案。

  • 如果您需要嵌套或动态投影,您可能需要投影方法而不是 DTO 方法。

    引用 official Spring doc详情。

    关于jpa - Spring 数据: when use Projection interfaces and DTO projections?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176316/

    相关文章:

    hibernate - AnnotationException : A Foreign key refering has the wrong number of column. 应该是 2

    jsf - 如果我尝试删除它,为什么 JPA 的行为就像我的实体已分离,但如果我编辑它却不是?

    java - key 'PRIMARY' 的重复条目使用 JPA 持久保存到数据库中

    spring - 我如何使用带有注解驱动配置的 Spring Data HBase

    java - Spring Data JPA - 删除一对多关系中的 child

    spring - 休息 : Extending CrudRepository for self-referencing entities throws an exception

    java - @PersistenceUnit 注释不会创建 EntityManageFactory emf=null

    java - 将变量声明为静态 : Unexpected behaviour

    java - 从 CSV 复制表(postgresql、spring data/hibernate)

    java - 从maven spring mvc创建表时出现问题