Skip to content

Commit 15e8ba3

Browse files
committed
spring-projects#201 - Added example for constructor expression in JPA projections.
1 parent bee8a81 commit 15e8ba3

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,13 @@ public interface CustomerRepository extends CrudRepository<Customer, Long> {
9595
* @return
9696
*/
9797
Page<CustomerProjection> findPagedProjectedBy(Pageable pageable);
98+
99+
/**
100+
* A DTO projection using a constructor expression in a manually declared query.
101+
*
102+
* @param firstname
103+
* @return
104+
*/
105+
@Query("select new example.springdata.jpa.projections.CustomerDto(c.firstname) from Customer c where c.firstname = ?1")
106+
Collection<CustomerDto> findDtoWithConstructorExpression(String firstname);
98107
}

jpa/example/src/test/java/example/springdata/jpa/projections/CustomerRepositoryIntegrationTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,15 @@ public void projectIndividualInstance() {
117117
assertThat(((TargetAware) projectedDave).getTarget(), is(instanceOf(Map.class)));
118118
}
119119

120+
@Test
121+
public void projectsDtoUsingConstructorExpression() {
122+
123+
Collection<CustomerDto> result = customers.findDtoWithConstructorExpression("Dave");
124+
125+
assertThat(result, hasSize(1));
126+
assertThat(result.iterator().next().getFirstname(), is("Dave"));
127+
}
128+
120129
@Test
121130
public void supportsProjectionInCombinationWithPagination() {
122131

0 commit comments

Comments
 (0)