DATAMONGO-2043 - Omit type hint when mapping simple types.

Original pull request: #589.
This commit is contained in:
Christoph Strobl
2018-08-06 13:46:39 +02:00
committed by Mark Paluch
parent 25507b995f
commit 47f9e3c739
2 changed files with 22 additions and 2 deletions

View File

@@ -351,10 +351,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
}
Class<?> entityType = obj.getClass();
boolean handledByCustomConverter = conversions.getCustomWriteTarget(entityType, DBObject.class) != null;
TypeInformation<? extends Object> type = ClassTypeInformation.from(entityType);
if (!handledByCustomConverter && !(dbo instanceof BasicDBList)) {
if (requiresTypeHint(entityType)) {
typeMapper.writeType(type, dbo);
}
@@ -363,6 +362,18 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
writeInternal(target, dbo, type);
}
/**
* Check if a given type requires a type hint {@literal aka _class attribute} when writing to the document.
*
* @param type must not be {@literal null}.
* @return true if not a simple type, collection or type with custom write target.
*/
private boolean requiresTypeHint(Class<?> type) {
return !conversions.isSimpleType(type) && !ClassUtils.isAssignable(Collection.class, type)
&& !conversions.hasCustomWriteTarget(type, DBObject.class);
}
/**
* Internal write conversion method which should be used for nested invocations.
*

View File

@@ -1853,6 +1853,15 @@ public class MappingMongoConverterUnitTests {
assertThat(converter.read(Attribute.class, source).value, is(instanceOf(List.class)));
}
@Test // DATAMONGO-2043
public void omitsTypeHintWhenWritingSimpleTypes() {
DBObject target = new BasicDBObject();
converter.write(new BasicDBObject("value", "FitzChivalry"), target);
assertThat(target.get("_class"), is(nullValue()));
}
static class GenericType<T> {
T content;
}