Skip to content

Commit 429dcbf

Browse files
committed
DATACMNS-867 - ReflectionRepositoryInvoker now avoids ConversionService for Optional creation.
We now manually create Optional instances as the ConversionService converts single-argument collections into an optional with only that element.
1 parent fe5d543 commit 429dcbf

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/main/java/org/springframework/data/repository/support/ReflectionRepositoryInvoker.java

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,16 +253,8 @@ private <T> T invoke(Method method, Object... arguments) {
253253

254254
@SuppressWarnings("unchecked")
255255
private <T> Optional<T> returnAsOptional(Object source) {
256-
257-
if (Optional.class.isInstance(source)) {
258-
return (Optional<T>) source;
259-
}
260-
261-
if (source == null) {
262-
return Optional.empty();
263-
}
264-
265-
return conversionService.convert(QueryExecutionConverters.unwrap(source), Optional.class);
256+
return (Optional<T>) (Optional.class.isInstance(source) ? source
257+
: Optional.ofNullable(QueryExecutionConverters.unwrap(source)));
266258
}
267259

268260
/**

src/test/java/org/springframework/data/repository/support/ReflectionRepositoryInvokerUnitTests.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,22 @@ public void convertsWrapperTypeToJdkOptional() {
254254
assertThat(invokeFindOne).isPresent();
255255
}
256256

257+
@Test // DATACMNS-867
258+
public void wrapsSingleElementCollectionIntoOptional() throws Exception {
259+
260+
ManualCrudRepository mock = mock(ManualCrudRepository.class);
261+
when(mock.findAll()).thenReturn(Arrays.asList(new Domain()));
262+
263+
Method method = ManualCrudRepository.class.getMethod("findAll");
264+
265+
Optional<Object> result = getInvokerFor(mock).invokeQueryMethod(method, new LinkedMultiValueMap<>(), Pageable.unpaged(),
266+
Sort.unsorted());
267+
268+
assertThat(result).hasValueSatisfying(it -> {
269+
assertThat(it).isInstanceOf(Collection.class);
270+
});
271+
}
272+
257273
private static RepositoryInvoker getInvokerFor(Object repository) {
258274

259275
RepositoryMetadata metadata = new DefaultRepositoryMetadata(repository.getClass().getInterfaces()[0]);

0 commit comments

Comments
 (0)