Skip to content

Commit a799301

Browse files
committed
DATAMONGO-1525 - Improved creation of empty collections, esp. EnumSet.
We now use more type information to create a better empty collection in the first place. The previous algorithm always used an empty HashSet plus a subsequent conversion using the raw collection type. Especially the latter caused problems for EnumSets as the conversion into one requires the presence of component type information. We now use Spring's collection factory and more available type information to create a proper collection in the first place and only rely on a subsequent conversion for arrays.
1 parent 9059a77 commit a799301

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -892,17 +892,17 @@ private Object readCollectionOrArray(TypeInformation<?> targetType, BasicDBList
892892

893893
Class<?> collectionType = targetType.getType();
894894

895-
if (sourceValue.isEmpty()) {
896-
return getPotentiallyConvertedSimpleRead(new HashSet<Object>(), collectionType);
897-
}
898-
899895
TypeInformation<?> componentType = targetType.getComponentType();
900896
Class<?> rawComponentType = componentType == null ? null : componentType.getType();
901897

902898
collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class;
903899
Collection<Object> items = targetType.getType().isArray() ? new ArrayList<Object>()
904900
: CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size());
905901

902+
if (sourceValue.isEmpty()) {
903+
return getPotentiallyConvertedSimpleRead(items, collectionType);
904+
}
905+
906906
if (!DBRef.class.equals(rawComponentType) && isCollectionOfDbRefWhereBulkFetchIsPossible(sourceValue)) {
907907
return bulkReadAndConvertDBRefs((List<DBRef>) (List) (sourceValue), componentType, path, rawComponentType);
908908
}

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2086,6 +2086,17 @@ public void readsPropertyFromNestedFieldCorrectly() {
20862086
assertThat(result.sample, is("value"));
20872087
}
20882088

2089+
/**
2090+
* @see DATAMONGO-1525
2091+
*/
2092+
@Test
2093+
public void readsEmptyEnumSet() {
2094+
2095+
DBObject source = new BasicDBObject("enumSet", new BasicDBList());
2096+
2097+
assertThat(converter.read(ClassWithEnumProperty.class, source).enumSet, is(EnumSet.noneOf(SampleEnum.class)));
2098+
}
2099+
20892100
static class GenericType<T> {
20902101
T content;
20912102
}

0 commit comments

Comments
 (0)