Example usage for org.springframework.data.mongodb.core.mapping MongoPersistentEntity doWithProperties

List of usage examples for org.springframework.data.mongodb.core.mapping MongoPersistentEntity doWithProperties

Introduction

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

Prototype

void doWithProperties(PropertyHandler<P> handler);

Source Link

Document

Applies the given PropertyHandler to all PersistentProperty s contained in this PersistentEntity .

Usage

From source file:com.epam.ta.reportportal.database.dao.ReportPortalRepositoryImpl.java

@Override
public void partialUpdate(T t) {
    ID id = getEntityInformation().getId(t);
    if (null == id) {
        throw new IllegalArgumentException("ID property should not be null");
    }// w w w .  jav a  2  s.c  om

    Update update = new Update();
    final MongoPersistentEntity<?> persistentEntity = mongoOperations.getConverter().getMappingContext()
            .getPersistentEntity(getEntityInformation().getJavaType());
    persistentEntity.doWithProperties((PropertyHandler<MongoPersistentProperty>) persistentProperty -> {
        if (!persistentEntity.isIdProperty(persistentProperty)) {
            Object value = Accessible.on(t).field(persistentProperty.getField()).getValue();
            if (null != value) {
                update.set(persistentProperty.getFieldName(), value);
            }
        }
    });

    WriteResult writeResult = mongoOperations.updateFirst(
            query(where(persistentEntity.getIdProperty().getFieldName()).is(id)), update,
            getEntityInformation().getCollectionName());
    if (1 != writeResult.getN()) {
        throw new IncorrectResultSizeDataAccessException(1, writeResult.getN());
    }
}

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;/* ww  w  .  j  ava2  s.co  m*/
    }

    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  w  w  w .j a va  2 s. co 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  ww  w  .  j ava  2  s . c  o m
    }

    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.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.");
        }//ww  w .  jav  a2s.  c  o m

        // 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);
    }
}