【问题标题】:how and where i get DTO object我如何以及在哪里获得 DTO 对象
【发布时间】:2023-03-03 01:47:01
【问题描述】:

我不明白什么时候需要通过SQL-query直接将投影投影到DTO中,什么时候需要使用Entity DTO转换,例如使用MapStruct工具等。 而如果你直接收到DTO,你推荐在哪一层做,应该在Service层还是在Repository(JpaRepository)? 有没有这方面的书籍或文章?

【问题讨论】:

    标签: jpa entity dto


    【解决方案1】:

    Spring Repository 允许使用构造函数投影在存储库中进行 DTO(例如使用 select new 语法时)。在我看来,最好的用例是性能。

    看这个帖子Why are interface projections much slower than constructor projections and entity projections in Spring Data JPA with Hibernate?

    它比较所有类型的预测:

    1. 实体投影
    2. 构造函数投影
    3. 界面投影
    4. 元组投影
    5. 动态投影

    这是结果:

    Entity projections took 161.61 ms on average out of 100 iterations.
    Constructor projections took 24.84 ms on average out of 100 iterations.
    Interface projections took 252.26 ms on average out of 100 iterations.
    Tuple projections took 21.41 ms on average out of 100 iterations.
    Dynamic projections took 23.62 ms on average out of 100 iterations.
    -----------------------------------------------------------------------
    One iteration retrieved (from DB) and projected 100 000 objects.
    -----------------------------------------------------------------------
    

    如您所见,构造函数投影确实比实体或接口投影快。因此,如果您需要速度,则必须在存储库中使用 DTO(即使这是好的或坏的做法......)

    此外,一个又好又胖的 JPQL DTO 查询避免了著名的 n+1 Hibernate 请求问题。

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 2011-11-11
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      相关资源
      最近更新 更多