Don't rely on collection to object conversion in spring-data-commons.

Original Pull Request #2241
Closes #2152
This commit is contained in:
Peter-Josef Meisch 2022-07-28 07:41:07 +02:00 committed by GitHub
parent 3e950b8053
commit 1f1076aa8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -30,6 +30,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.MapAccessor;
import org.springframework.core.CollectionFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.convert.CustomConversions;
@ -567,6 +568,29 @@ public class MappingElasticsearchConverter
return Enum.valueOf((Class<Enum>) target, value.toString());
}
try {
return conversionService.convert(value, target);
} catch (ConverterNotFoundException e) {
return convertFromCollectionToObject(value, target);
}
}
/**
* we need the conversion from a collection to the first element for example in the case when reading the
* constructor parameter of an entity from a scripted return. Originally this was handle in the conversionService,
* but will be removed from spring-data-commons, so we do it here
*/
@Nullable
private Object convertFromCollectionToObject(Object value, @Nullable Class<?> target) {
if (value.getClass().isArray()) {
value = Arrays.asList(value);
}
if (value instanceof Collection<?> collection && !collection.isEmpty()) {
value = collection.iterator().next();
}
return conversionService.convert(value, target);
}