Skip to content

Commit e658648

Browse files
committed
Add documentation.
See #3076
1 parent 3c3d5c5 commit e658648

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
@@ -10,6 +10,41 @@ NOTE: It is important to note that <<projections.dtos,Class-based projections>>
1010
And it's important to point out that class-based projections do not work with native queries AT ALL.
1111
As a workaround you may use named queries with `ResultSetMapping` or the Hibernate-specific javadoc:{hibernatejavadocurl}org.hibernate.query.ResultListTransformer[]
1212

13+
== DTO Projection JPQL Query Rewriting
14+
15+
JPQL queries allow selection of the root object, individual properties, and DTO objects through constructor expressions.
16+
Using a constructor expression can quickly add a lot of text to a query and make it difficult to read the actual query.
17+
Spring Data JPA can support you with your JPQL queries by introducing constructor expressions for your convenience.
18+
19+
Consider the following queries:
20+
21+
.Projection Queries
22+
====
23+
[source,java]
24+
----
25+
interface UserRepository extends Repository<User, Long> {
26+
27+
@Query("SELECT u FROM USER u") <1>
28+
List<UserDto> findByLastname(String lastname);
29+
30+
@Query("SELECT u.firstname, u.lastname FROM USER u") <2>
31+
List<UserDto> findMultipleColumnsByLastname(String lastname);
32+
}
33+
34+
record UserDto(String firstname, String lastname){}
35+
----
36+
37+
<1> Selection of the top-level entity.
38+
This query gets rewritten to `SELECT new UserDto(u.firstname, u.lastname) FROM USER u`.
39+
<2> Multi-select of `firstname` and `lastname` properties.
40+
This query gets rewritten to `SELECT new UserDto(u.firstname, u.lastname) FROM USER u`.
41+
====
42+
43+
Repository query methods that return a DTO projection type (a Java type outside the domain type hierarchy) are subject for query rewriting.
44+
If an `@Query`-annotated query already uses constructor expressions, then Spring Data backs off and doesn't apply DTO constructor expression rewriting.
45+
46+
Make sure that your DTO types provide an all-args constructor for the projection, otherwise the query will fail.
47+
1348
include::{commons}@data-commons::page$repositories/projections-interface.adoc[leveloffset=1]
1449

1550
include::{commons}@data-commons::page$repositories/projections-class.adoc[leveloffset=1]

0 commit comments

Comments
 (0)