Skip to content

Commit ff50ae4

Browse files
committed
DATAJDBC-124 - findById now returns Optional.empty when no data is found.
The uderlying JdbcEntityTemplate still throws exceptions coming from the NamedParameterJdbcTemplate.
1 parent 1d63be8 commit ff50ae4

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

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

+6-2
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
import java.util.List;
2020
import java.util.Optional;
2121

22+
import org.springframework.dao.EmptyResultDataAccessException;
2223
import org.springframework.data.jdbc.core.JdbcEntityOperations;
2324
import org.springframework.data.jdbc.core.JdbcEntityTemplate;
24-
import org.springframework.data.jdbc.mapping.model.JdbcPersistentEntity;
2525
import org.springframework.data.jdbc.mapping.model.JdbcPersistentEntityInformation;
2626
import org.springframework.data.repository.CrudRepository;
2727

@@ -76,7 +76,11 @@ public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
7676
@Override
7777
public Optional<T> findById(ID id) {
7878

79-
return Optional.ofNullable(entityOperations.findById(id, entityInformation.getJavaType()));
79+
try {
80+
return Optional.of(entityOperations.findById(id, entityInformation.getJavaType()));
81+
} catch (EmptyResultDataAccessException ex) {
82+
return Optional.empty();
83+
}
8084
}
8185

8286
/*

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

+8
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,14 @@ public void updateMany() {
233233
.containsExactlyInAnyOrder(entity.getName(), other.getName());
234234
}
235235

236+
@Test // DATAJDBC-112
237+
public void findByIdReturnsEmptyWhenNoneFound() {
238+
239+
// NOT saving anything, so DB is empty
240+
241+
assertThat(repository.findById(-1L)).isEmpty();
242+
}
243+
236244
private static DummyEntity createDummyEntity() {
237245

238246
DummyEntity entity = new DummyEntity();

0 commit comments

Comments
 (0)