Skip to content

Commit c8bc94d

Browse files
mp911dechristophstrobl
authored andcommitted
Add documentation.
See #3076
1 parent e0348c8 commit c8bc94d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/main/antora/modules/ROOT/pages/repositories/projections.adoc

+35
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,41 @@ When using <<projections.dtos,Class-based projections>> with JPQL, you must use
3636
(Note the usage of a FQDN for the DTO type!) This JPQL expression can be used in `@Query` annotations as well where you define any named queries.
3737
As a workaround you may use named queries with `ResultSetMapping` or the Hibernate-specific javadoc:{hibernatejavadocurl}org.hibernate.query.ResultListTransformer[]
3838

39+
===== DTO Projection JPQL Query Rewriting
40+
41+
JPQL queries allow selection of the root object, individual properties, and DTO objects through constructor expressions.
42+
Using a constructor expression can quickly add a lot of text to a query and make it difficult to read the actual query.
43+
Spring Data JPA can support you with your JPQL queries by introducing constructor expressions for your convenience.
44+
45+
Consider the following queries:
46+
47+
.Projection Queries
48+
====
49+
[source,java]
50+
----
51+
interface UserRepository extends Repository<User, Long> {
52+
53+
@Query("SELECT u FROM USER u") <1>
54+
List<UserDto> findByLastname(String lastname);
55+
56+
@Query("SELECT u.firstname, u.lastname FROM USER u") <2>
57+
List<UserDto> findMultipleColumnsByLastname(String lastname);
58+
}
59+
60+
record UserDto(String firstname, String lastname){}
61+
----
62+
63+
<1> Selection of the top-level entity.
64+
This query gets rewritten to `SELECT new UserDto(u.firstname, u.lastname) FROM USER u`.
65+
<2> Multi-select of `firstname` and `lastname` properties.
66+
This query gets rewritten to `SELECT new UserDto(u.firstname, u.lastname) FROM USER u`.
67+
====
68+
69+
Repository query methods that return a DTO projection type (a Java type outside the domain type hierarchy) are subject for query rewriting.
70+
If an `@Query`-annotated query already uses constructor expressions, then Spring Data backs off and doesn't apply DTO constructor expression rewriting.
71+
72+
Make sure that your DTO types provide an all-args constructor for the projection, otherwise the query will fail.
73+
3974
==== Native Queries
4075

4176
When using <<projections.dtos,Class-based projections>>, their usage requires slightly more consideration depending on your :

0 commit comments

Comments
 (0)