【发布时间】:2023-03-03 01:47:01
【问题描述】:
我不明白什么时候需要通过SQL-query直接将投影投影到DTO中,什么时候需要使用Entity DTO转换,例如使用MapStruct工具等。 而如果你直接收到DTO,你推荐在哪一层做,应该在Service层还是在Repository(JpaRepository)? 有没有这方面的书籍或文章?
【问题讨论】:
我不明白什么时候需要通过SQL-query直接将投影投影到DTO中,什么时候需要使用Entity DTO转换,例如使用MapStruct工具等。 而如果你直接收到DTO,你推荐在哪一层做,应该在Service层还是在Repository(JpaRepository)? 有没有这方面的书籍或文章?
【问题讨论】:
Spring Repository 允许使用构造函数投影在存储库中进行 DTO(例如使用 select new 语法时)。在我看来,最好的用例是性能。
它比较所有类型的预测:
这是结果:
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 请求问题。
【讨论】: