From 1f1076aa8bc6a88155c1a31cd55c8ba1d4f06455 Mon Sep 17 00:00:00 2001 From: Peter-Josef Meisch Date: Thu, 28 Jul 2022 07:41:07 +0200 Subject: [PATCH] Don't rely on collection to object conversion in spring-data-commons. Original Pull Request #2241 Closes #2152 --- .../MappingElasticsearchConverter.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java b/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java index 9613ed04f..9d625ee5d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java @@ -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) 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); }