Skip to content

Commit 7401e5e

Browse files
christophstroblmp911de
authored andcommitted
DATAMONGO-1831 - Fix array type conversion for empty source.
We now make sure that we convert empty sources to the corresponding target type. This prevents entity instantiation from failing due to incorrect argument types when invoking the constructor. Original pull request: spring-projects#520.
1 parent ad995fd commit 7401e5e

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -954,7 +954,7 @@ private Object readCollectionOrArray(TypeInformation<?> targetType, List sourceV
954954
: CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size());
955955

956956
if (sourceValue.isEmpty()) {
957-
return getPotentiallyConvertedSimpleRead(items, collectionType);
957+
return getPotentiallyConvertedSimpleRead(items, targetType.getType());
958958
}
959959

960960
if (!DBRef.class.equals(rawComponentType) && isCollectionOfDbRefWhereBulkFetchIsPossible(sourceValue)) {

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java

+25
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
import static org.mockito.Mockito.*;
2222
import static org.springframework.data.mongodb.core.DocumentTestUtils.*;
2323

24+
import lombok.RequiredArgsConstructor;
25+
2426
import java.math.BigDecimal;
2527
import java.math.BigInteger;
2628
import java.net.URL;
@@ -1803,6 +1805,22 @@ public void failsReadingDocumentIntoSimpleType() {
18031805
converter.read(TypeWithMapOfLongValues.class, source);
18041806
}
18051807

1808+
@Test // DATAMONGO-1831
1809+
public void shouldConvertArrayInConstructorCorrectly() {
1810+
1811+
org.bson.Document source = new org.bson.Document("array", Collections.emptyList());
1812+
1813+
assertThat(converter.read(WithArrayInConstructor.class, source).array, is(emptyArray()));
1814+
}
1815+
1816+
@Test // DATAMONGO-1831
1817+
public void shouldConvertNullForArrayInConstructorCorrectly() {
1818+
1819+
org.bson.Document source = new org.bson.Document();
1820+
1821+
assertThat(converter.read(WithArrayInConstructor.class, source).array, is(nullValue()));
1822+
}
1823+
18061824
static class GenericType<T> {
18071825
T content;
18081826
}
@@ -2157,4 +2175,11 @@ static class TypeWithPropertyInNestedField {
21572175
static class TypeWithMapOfLongValues {
21582176
Map<String, Long> map;
21592177
}
2178+
2179+
@RequiredArgsConstructor
2180+
static class WithArrayInConstructor {
2181+
2182+
final String[] array;
2183+
2184+
}
21602185
}

0 commit comments

Comments
 (0)