Example usage for org.springframework.data.mongodb.core.mapping MongoPersistentProperty getFieldName

List of usage examples for org.springframework.data.mongodb.core.mapping MongoPersistentProperty getFieldName

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.mapping MongoPersistentProperty getFieldName.

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field a property is persisted to.

Usage

From source file:org.oasis.datacore.sdk.data.spring.DatacoreMappingMongoConverter.java

protected void writeInternal(Object obj, final DBObject dbo, MongoPersistentEntity<?> entity) {

    if (obj == null) {
        return;//  w w  w  . java2s  .  c  om
    }

    if (null == entity) {
        throw new MappingException("No mapping metadata found for entity of type " + obj.getClass().getName());
    }

    final BeanWrapper<MongoPersistentEntity<Object>, Object> wrapper = BeanWrapper.create(obj,
            conversionService);
    final MongoPersistentProperty idProperty = entity.getIdProperty();

    if (!dbo.containsField("_id") && null != idProperty) {

        boolean fieldAccessOnly = idProperty.usePropertyAccess() ? false : useFieldAccessOnly;

        try {
            Object id = wrapper.getProperty(idProperty, Object.class, fieldAccessOnly);
            dbo.put("_id", idMapper.convertId(id));
        } catch (ConversionException ignored) {
        }
    }

    // Write the properties
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            if (prop.equals(idProperty)) {
                return;
            }

            boolean fieldAccessOnly = prop.usePropertyAccess() ? false : useFieldAccessOnly;

            Object propertyObj = wrapper.getProperty(prop, prop.getType(), fieldAccessOnly);

            //if (null != propertyObj) { // [Ozwillo] HACK to allow unset / set to null at save
            if (/*[Ozwillo] HACK*/null != propertyObj
                    && /*[Ozwillo] END*/!conversions.isSimpleType(propertyObj.getClass())) {
                writePropertyInternal(propertyObj, dbo, prop);
            } else {
                writeSimpleInternal(propertyObj, dbo, prop.getFieldName());
            }
            //} // [Ozwillo] HACK
        }
    });

    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Class<?> type = inverseProp.getType();
            Object propertyObj = wrapper.getProperty(inverseProp, type, useFieldAccessOnly);
            //if (null != propertyObj) { // [Ozwillo] HACK to allow unset / set to null at save
            writePropertyInternal(propertyObj, dbo, inverseProp);
            //} // [Ozwillo] HACK
        }
    });

    // [Ozwillo] HACK to persist Datacore model fields at root level NOT FOR NOW
    /*if ("DCEntity".equals(entity.getName())) {
       DCEntity dcEntity = (DCEntity) object;
       DCModel dcModel = dcModelService.getModel(dcEntity.getType());
       for (DCField dcField : dcModel.getAllFields()) {
            
       }
    }*/
}

From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo) {

    final StandardEvaluationContext spelCtx = new StandardEvaluationContext(dbo);
    spelCtx.addPropertyAccessor(DBObjectPropertyAccessor.INSTANCE);

    if (applicationContext != null) {
        spelCtx.setBeanResolver(new BeanFactoryResolver(applicationContext));
    }//from   ww  w  .  j  av  a 2  s  . c o  m

    final MappedConstructor constructor = new MappedConstructor(entity, mappingContext);

    SpELAwareParameterValueProvider delegate = new SpELAwareParameterValueProvider(spelExpressionParser,
            spelCtx);
    ParameterValueProvider provider = new DelegatingParameterValueProvider(constructor, dbo, delegate);

    final BeanWrapper<MongoPersistentEntity<S>, S> wrapper = BeanWrapper.create(entity, provider,
            conversionService);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            boolean isConstructorProperty = constructor.isConstructorParameter(prop);
            boolean hasValueForProperty = dbo.containsField(prop.getFieldName());

            if (!hasValueForProperty || isConstructorProperty) {
                return;
            }

            Object obj = getValueInternal(prop, dbo, spelCtx, prop.getSpelExpression());
            wrapper.setProperty(prop, obj, useFieldAccessOnly);
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Object obj = getValueInternal(inverseProp, dbo, spelCtx, inverseProp.getSpelExpression());
            try {
                wrapper.setProperty(inverseProp, obj);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    return wrapper.getBean();
}

From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java

protected void writeInternal(Object obj, final DBObject dbo, MongoPersistentEntity<?> entity) {

    if (obj == null) {
        return;/*from  w  ww .  j  a  va2 s.c  om*/
    }

    if (null == entity) {
        throw new MappingException("No mapping metadata found for entity of type " + obj.getClass().getName());
    }

    final BeanWrapper<MongoPersistentEntity<Object>, Object> wrapper = BeanWrapper.create(obj,
            conversionService);

    // Write the ID
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    if (!dbo.containsField("_id") && null != idProperty) {

        try {
            Object id = wrapper.getProperty(idProperty, Object.class, useFieldAccessOnly);
            dbo.put("_id", idMapper.convertId(id));
        } catch (ConversionException ignored) {
        }
    }

    // Write the properties
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            if (prop.equals(idProperty)) {
                return;
            }

            Object propertyObj = wrapper.getProperty(prop, prop.getType(), useFieldAccessOnly);

            if (null != propertyObj) {
                if (!conversions.isSimpleType(propertyObj.getClass())) {
                    writePropertyInternal(propertyObj, dbo, prop);
                } else {
                    writeSimpleInternal(propertyObj, dbo, prop.getFieldName());
                }
            }
        }
    });

    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Class<?> type = inverseProp.getType();
            Object propertyObj = wrapper.getProperty(inverseProp, type, useFieldAccessOnly);
            if (null != propertyObj) {
                writePropertyInternal(propertyObj, dbo, inverseProp);
            }
        }
    });
}

From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java

@SuppressWarnings({ "unchecked" })
protected void writePropertyInternal(Object obj, DBObject dbo, MongoPersistentProperty prop) {

    if (obj == null) {
        return;//from w  w w.  j  a v a2s .co  m
    }

    String name = prop.getFieldName();
    TypeInformation<?> valueType = ClassTypeInformation.from(obj.getClass());
    TypeInformation<?> type = prop.getTypeInformation();

    if (valueType.isCollectionLike()) {
        DBObject collectionInternal = createCollection(asCollection(obj), prop);
        dbo.put(name, collectionInternal);
        return;
    }

    if (valueType.isMap()) {
        BasicDBObject mapDbObj = new BasicDBObject();
        writeMapInternal((Map<Object, Object>) obj, mapDbObj, type);
        dbo.put(name, mapDbObj);
        return;
    }

    if (prop.isDbReference()) {
        DBRef dbRefObj = createDBRef(obj, prop.getDBRef());
        if (null != dbRefObj) {
            dbo.put(name, dbRefObj);
            return;
        }
    }

    // Lookup potential custom target type
    Class<?> basicTargetType = conversions.getCustomWriteTarget(obj.getClass(), null);

    if (basicTargetType != null) {
        dbo.put(name, conversionService.convert(obj, basicTargetType));
        return;
    }

    BasicDBObject propDbObj = new BasicDBObject();
    addCustomTypeKeyIfNecessary(type, obj, propDbObj);

    MongoPersistentEntity<?> entity = isSubtype(prop.getType(), obj.getClass())
            ? mappingContext.getPersistentEntity(obj.getClass())
            : mappingContext.getPersistentEntity(type);

    writeInternal(obj, propDbObj, entity);
    dbo.put(name, propDbObj);
}

From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java

@SuppressWarnings("unchecked")
protected Object getValueInternal(MongoPersistentProperty prop, DBObject dbo, StandardEvaluationContext ctx,
        String spelExpr) {//from  ww  w  .j  a v a2  s.  c om

    Object o;
    if (null != spelExpr) {
        Expression x = spelExpressionParser.parseExpression(spelExpr);
        o = x.getValue(ctx);
    } else {

        Object sourceValue = dbo.get(prop.getFieldName());

        if (sourceValue == null) {
            return null;
        }

        Class<?> propertyType = prop.getType();

        if (conversions.hasCustomReadTarget(sourceValue.getClass(), propertyType)) {
            return conversionService.convert(sourceValue, propertyType);
        }

        if (sourceValue instanceof DBRef) {
            sourceValue = ((DBRef) sourceValue).fetch();
        }
        if (sourceValue instanceof DBObject) {
            if (prop.isMap()) {
                return readMap(prop.getTypeInformation(), (DBObject) sourceValue);
            } else if (prop.isArray() && sourceValue instanceof BasicDBObject
                    && ((DBObject) sourceValue).keySet().size() == 0) {
                // It's empty
                return Array.newInstance(prop.getComponentType(), 0);
            } else if (prop.isCollectionLike() && sourceValue instanceof BasicDBList) {
                return readCollectionOrArray(
                        (TypeInformation<? extends Collection<?>>) prop.getTypeInformation(),
                        (BasicDBList) sourceValue);
            }

            TypeInformation<?> toType = typeMapper.readType((DBObject) sourceValue, prop.getTypeInformation());

            // It's a complex object, have to read it in
            if (toType != null) {
                // TODO: why do we remove the type?
                // dbo.removeField(CUSTOM_TYPE_KEY);
                o = read(toType, (DBObject) sourceValue);
            } else {
                o = read(mappingContext.getPersistentEntity(prop.getTypeInformation()), (DBObject) sourceValue);
            }
        } else {
            o = sourceValue;
        }
    }
    return o;
}

From source file:org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator.java

protected void checkForIndexes(final MongoPersistentEntity<?> entity) {
    final Class<?> type = entity.getType();
    if (!classesSeen.containsKey(type)) {
        if (log.isDebugEnabled()) {
            log.debug("Analyzing class " + type + " for index information.");
        }/*from ww w. ja  v a2s. com*/

        // Make sure indexes get created
        if (type.isAnnotationPresent(CompoundIndexes.class)) {
            CompoundIndexes indexes = type.getAnnotation(CompoundIndexes.class);
            for (CompoundIndex index : indexes.value()) {

                String indexColl = StringUtils.hasText(index.collection()) ? index.collection()
                        : entity.getCollection();
                DBObject definition = (DBObject) JSON.parse(index.def());

                ensureIndex(indexColl, index.name(), definition, index.unique(), index.dropDups(),
                        index.sparse());

                if (log.isDebugEnabled()) {
                    log.debug("Created compound index " + index);
                }
            }
        }

        entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
            public void doWithPersistentProperty(MongoPersistentProperty persistentProperty) {

                Field field = persistentProperty.getField();

                if (field.isAnnotationPresent(Indexed.class)) {

                    Indexed index = field.getAnnotation(Indexed.class);
                    String name = index.name();

                    if (!StringUtils.hasText(name)) {
                        name = persistentProperty.getFieldName();
                    } else {
                        if (!name.equals(field.getName()) && index.unique() && !index.sparse()) {
                            // Names don't match, and sparse is not true. This situation will generate an error on the server.
                            if (log.isWarnEnabled()) {
                                log.warn("The index name " + name + " doesn't match this property name: "
                                        + field.getName()
                                        + ". Setting sparse=true on this index will prevent errors when inserting documents.");
                            }
                        }
                    }

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    int direction = index.direction() == IndexDirection.ASCENDING ? 1 : -1;
                    DBObject definition = new BasicDBObject(persistentProperty.getFieldName(), direction);

                    ensureIndex(collection, name, definition, index.unique(), index.dropDups(), index.sparse());

                    if (log.isDebugEnabled()) {
                        log.debug("Created property index " + index);
                    }

                } else if (field.isAnnotationPresent(GeoSpatialIndexed.class)) {

                    GeoSpatialIndexed index = field.getAnnotation(GeoSpatialIndexed.class);

                    GeospatialIndex indexObject = new GeospatialIndex(persistentProperty.getFieldName());
                    indexObject.withMin(index.min()).withMax(index.max());
                    indexObject.named(StringUtils.hasText(index.name()) ? index.name() : field.getName());

                    String collection = StringUtils.hasText(index.collection()) ? index.collection()
                            : entity.getCollection();
                    mongoDbFactory.getDb().getCollection(collection).ensureIndex(indexObject.getIndexKeys(),
                            indexObject.getIndexOptions());

                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Created %s for entity %s in collection %s! ", indexObject,
                                entity.getType(), collection));
                    }
                }
            }
        });

        classesSeen.put(type, true);
    }
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

/**
 * Returns a {@link Query} for the given entity by its id.
 * /*from  w  w w.  j  ava2s  .  com*/
 * @param object must not be {@literal null}.
 * @return
 */
private Query getIdQueryFor(Object object) {

    Assert.notNull(object);

    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(object.getClass());
    MongoPersistentProperty idProp = entity.getIdProperty();

    if (idProp == null) {
        throw new MappingException("No id property found for object of type " + entity.getType().getName());
    }

    ConversionService service = mongoConverter.getConversionService();
    Object idProperty = null;

    idProperty = BeanWrapper.create(object, service).getProperty(idProp, Object.class, true);
    return new Query(where(idProp.getFieldName()).is(idProperty));
}