DATADOC-130 - Convert map key type to discovered generic key type.

Reding values into a map assumed map keys to be String values. We know leverage the conversion service to convert the key to the type we discover from the generics property information.
This commit is contained in:
Oliver Gierke
2011-05-13 12:45:38 +02:00
parent 41e49ad3e2
commit 94e4d2b095
2 changed files with 25 additions and 4 deletions

View File

@@ -630,16 +630,20 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
// We have to find a potentially stored class to be used first.
Class<?> toType = findTypeToBeUsed((DBObject) dbObj);
Map<String, Object> m = new LinkedHashMap<String, Object>();
Map<Object, Object> m = new LinkedHashMap<Object, Object>();
for (Map.Entry<String, Object> entry : ((Map<String, Object>) ((DBObject) dbObj).toMap()).entrySet()) {
if (entry.getKey().equals(CUSTOM_TYPE_KEY)) {
continue;
}
Class<?> keyType = prop.getComponentType();
Object key = conversionService.convert(entry.getKey(), keyType);
if (null != entry.getValue() && entry.getValue() instanceof DBObject) {
m.put(entry.getKey(), read((null != toType ? toType : prop.getMapValueType()), (DBObject) entry.getValue()));
m.put(key, read((null != toType ? toType : prop.getMapValueType()), (DBObject) entry.getValue()));
} else {
m.put(entry.getKey(), entry.getValue());
m.put(key, entry.getValue());
}
}
return m;

View File

@@ -99,7 +99,7 @@ public class MappingMongoConverterUnitTests {
* @see DATADOC-130
*/
@Test
public void convertsMapTypeCorrectly() {
public void writesMapTypeCorrectly() {
Map<Locale, String> map = Collections.singletonMap(Locale.US, "Foo");
@@ -109,6 +109,19 @@ public class MappingMongoConverterUnitTests {
assertThat(dbObject.get(Locale.US.toString()).toString(), is("Foo"));
}
/**
* @see DATADOC-130
*/
@Test
public void readsMapWithCustomKeyTypeCorrectly() {
DBObject mapObject = new BasicDBObject(Locale.US.toString(), "Value");
DBObject dbObject = new BasicDBObject("map", mapObject);
ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, dbObject);
assertThat(result.map.get(Locale.US), is("Value"));
}
/**
* @see DATADOC-128
*/
@@ -162,6 +175,10 @@ public class MappingMongoConverterUnitTests {
LocalDate birthDate;
}
static class ClassWithMapProperty {
Map<Locale, String> map;
}
public static class BirthDateContainer {
LocalDate birthDate;
}