From 34fe9d2720e9402db7708b9101011266d9e00d5a Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Thu, 18 Aug 2016 15:36:01 +0200 Subject: [PATCH] #206 - Added more projection examples in JPA. Added another one that shows projections can be wrapped into an Optional. --- .../springdata/jpa/projections/CustomerRepository.java | 9 +++++++++ .../projections/CustomerRepositoryIntegrationTest.java | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java b/jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java index 4031ab6f..752c3e88 100644 --- a/jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java +++ b/jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java @@ -16,6 +16,7 @@ package example.springdata.jpa.projections; import java.util.Collection; +import java.util.Optional; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; @@ -104,4 +105,12 @@ public interface CustomerRepository extends CrudRepository { */ @Query("select new example.springdata.jpa.projections.CustomerDto(c.firstname) from Customer c where c.firstname = ?1") Collection findDtoWithConstructorExpression(String firstname); + + /** + * A projection wrapped into an {@link Optional}. + * + * @param lastname + * @return + */ + Optional findOptionalProjectionByLastname(String lastname); } diff --git a/jpa/example/src/test/java/example/springdata/jpa/projections/CustomerRepositoryIntegrationTest.java b/jpa/example/src/test/java/example/springdata/jpa/projections/CustomerRepositoryIntegrationTest.java index ca20e9cc..4573ae37 100644 --- a/jpa/example/src/test/java/example/springdata/jpa/projections/CustomerRepositoryIntegrationTest.java +++ b/jpa/example/src/test/java/example/springdata/jpa/projections/CustomerRepositoryIntegrationTest.java @@ -134,4 +134,9 @@ public class CustomerRepositoryIntegrationTest { assertThat(page.getContent().get(0).getFirstname(), is("Carter")); } + + @Test + public void appliesProjectionToOptional() { + assertThat(customers.findOptionalProjectionByLastname("Beauford").isPresent(), is(true)); + } }