Search in sources :

Example 1 with TypeInformation

use of org.springframework.data.util.TypeInformation in project spring-data-mongodb by spring-projects.

the class MappingMongoConverter method writeMapInternal.

/**
 * Writes the given {@link Map} to the given {@link Document} considering the given {@link TypeInformation}.
 *
 * @param obj must not be {@literal null}.
 * @param bson must not be {@literal null}.
 * @param propertyType must not be {@literal null}.
 * @return
 */
protected Bson writeMapInternal(Map<Object, Object> obj, Bson bson, TypeInformation<?> propertyType) {
    for (Map.Entry<Object, Object> entry : obj.entrySet()) {
        Object key = entry.getKey();
        Object val = entry.getValue();
        if (conversions.isSimpleType(key.getClass())) {
            String simpleKey = prepareMapKey(key);
            if (val == null || conversions.isSimpleType(val.getClass())) {
                writeSimpleInternal(val, bson, simpleKey);
            } else if (val instanceof Collection || val.getClass().isArray()) {
                addToMap(bson, simpleKey, writeCollectionInternal(asCollection(val), propertyType.getMapValueType(), new BasicDBList()));
            } else {
                Document document = new Document();
                TypeInformation<?> valueTypeInfo = propertyType.isMap() ? propertyType.getMapValueType() : ClassTypeInformation.OBJECT;
                writeInternal(val, document, valueTypeInfo);
                addToMap(bson, simpleKey, document);
            }
        } else {
            throw new MappingException("Cannot use a complex object as a key value.");
        }
    }
    return bson;
}
Also used : BasicDBList(com.mongodb.BasicDBList) Collection(java.util.Collection) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Document(org.bson.Document) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) TypeInformation(org.springframework.data.util.TypeInformation) MappingException(org.springframework.data.mapping.MappingException)

Aggregations

BasicDBList (com.mongodb.BasicDBList)1 BasicDBObject (com.mongodb.BasicDBObject)1 DBObject (com.mongodb.DBObject)1 Collection (java.util.Collection)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 Document (org.bson.Document)1 MappingException (org.springframework.data.mapping.MappingException)1 ClassTypeInformation (org.springframework.data.util.ClassTypeInformation)1 TypeInformation (org.springframework.data.util.TypeInformation)1