I do not understand when you need to get a projection directly into the DTO through the SQL-query, and when you need to use the Entity <> DTO conversion, for example, with such MapStruct tools, etc. And if you receive the DTO directly, on which layer do you recommend doing this, should it be in the Service layer or in the Repository (JpaRepository)? Are there any books or articles about this?
Asked
Active
Viewed 231 times
1 Answers
1
Spring Repository allows DTO in repository with Constructor Projection (when using for example the select new
syntax). According to me, the best use case is for performance.
Look at this post Why are interface projections much slower than constructor projections and entity projections in Spring Data JPA with Hibernate?
It compares all kind of projections :
- Entity projection
- Constructor projection
- Interface projection
- Tuple projection
- Dynamic projection
And here is the results :
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.
-----------------------------------------------------------------------
As you can see Constructor projection is really faster than Entity or Interface projection. So if you need speed, you'll have to use DTO in repository (even if it's good or bad practice...)
Moreover a good and fat JPQL DTO query avoid the famous n+1 Hibernate request problem.

Maneki
- 307
- 2
- 4