Browse Source

DATAJDBC-124 - findById now returns Optional.empty when no data is found.

The uderlying JdbcEntityTemplate still throws exceptions coming from the NamedParameterJdbcTemplate.
pull/15/head
Jens Schauder 8 years ago committed by Greg Turnquist
parent
commit
2067fb6952
No known key found for this signature in database
GPG Key ID: CB2FA4D512B5C413
  1. 8
      src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java
  2. 8
      src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java

8
src/main/java/org/springframework/data/jdbc/repository/SimpleJdbcRepository.java

@ -19,9 +19,9 @@ import java.util.ArrayList; @@ -19,9 +19,9 @@ import java.util.ArrayList;
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 class SimpleJdbcRepository<T, ID> implements CrudRepository<T, ID> { @@ -76,7 +76,11 @@ public class SimpleJdbcRepository<T, ID> implements CrudRepository<T, ID> {
@Override
public Optional<T> 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();
}
}
/*

8
src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryIntegrationTests.java

@ -233,6 +233,14 @@ public class JdbcRepositoryIntegrationTests { @@ -233,6 +233,14 @@ public class JdbcRepositoryIntegrationTests {
.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();

Loading…
Cancel
Save