diff --git a/pom.xml b/pom.xml index 4ffa5540e7..742f52df25 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.springframework.data spring-data-jdbc - 1.0.0.BUILD-SNAPSHOT + 1.0.0.DATAJDBC-124-SNAPSHOT Spring Data JDBC Spring Data module for JDBC repositories. diff --git a/src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java b/src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java index cbd2102bb6..9ec47855b9 100644 --- a/src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java +++ b/src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java @@ -19,9 +19,9 @@ import java.util.List; import java.util.Optional; +import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.data.jdbc.core.JdbcEntityOperations; import org.springframework.data.jdbc.core.JdbcEntityTemplate; -import org.springframework.data.jdbc.mapping.model.JdbcPersistentEntity; import org.springframework.data.jdbc.mapping.model.JdbcPersistentEntityInformation; import org.springframework.data.repository.CrudRepository; @@ -76,7 +76,11 @@ public Iterable saveAll(Iterable entities) { @Override public Optional findById(ID id) { - return Optional.ofNullable(entityOperations.findById(id, entityInformation.getJavaType())); + try { + return Optional.of(entityOperations.findById(id, entityInformation.getJavaType())); + } catch (EmptyResultDataAccessException ex) { + return Optional.empty(); + } } /* diff --git a/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java b/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java index c7e9d67d5e..8f9003d26b 100644 --- a/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java +++ b/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java @@ -233,6 +233,14 @@ public void updateMany() { .containsExactlyInAnyOrder(entity.getName(), other.getName()); } + @Test // DATAJDBC-112 + public void findByIdReturnsEmptyWhenNoneFound() { + + // NOT saving anything, so DB is empty + + assertThat(repository.findById(-1L)).isEmpty(); + } + private static DummyEntity createDummyEntity() { DummyEntity entity = new DummyEntity();