Updates foreign keys into master table.

@param metadata
the metadata
@param id
the id
@param relationHolders
the relation holders
6502
private void updateForeignKeys(EntityMetadata metadata, Object id, List<RelationHolder> relationHolders)
    {
        for (RelationHolder rh : relationHolders)
        {
            String linkName = rh.getRelationName();
            Object linkValue = rh.getRelationValue();
            if (linkName != null && linkValue != null)
            {

                // String fieldName = metadata.getFieldName(linkName);

                String clause = getFromClause(metadata.getSchema(), metadata.getTableName());
                // String updateSql = "Update " +
                // metadata.getEntityClazz().getSimpleName() + " SET " +
                // fieldName + "= '" + linkValue + "' WHERE "
                // + ((AbstractAttribute) metadata.getIdAttribute()).getName() +
                // " = '" + id + "'";

                String updateSql = "Update " + clause + " SET " + linkName + "= '" + linkValue + "' WHERE "
                        + ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName() + " = '" + id + "'";

                onNativeUpdate(updateSql, null);
            }
        }
    }
1346772
public function setRelatedId( $id )
	{
		if ( $id === $this->getRelatedId() ) { return; }
		$id = (int) $id;
		$this->_values['relatedid'] = $id;
		$this->setModified();
	}
1144550
public function setMeta(string $key, $value)
    {
        if ($this->hasMeta($key)) {
            $meta = $this->getMetaRecord($key);
            $meta->setAttribute('value', $value);
            $meta->save();
        } else {
            $meta = $this->makeMeta($key, $value);
            $this->meta()->save($meta);
        }

        // Update cached relationship, if necessary.
        if ($this->relationLoaded('meta')) {
            $this->meta[$key] = $meta;
        }
    }
367677
@Override
    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)
    {
        // taking field's type as foreign entity, ignoring "targetEntity"
        Class<?> targetEntity = relationField.getType();

        ManyToOne ann = relationField.getAnnotation(ManyToOne.class);
        Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(), Arrays.asList(ann.cascade()),
                ann.optional(), null, // mappedBy is null
                Relation.ForeignKey.MANY_TO_ONE);

        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

        if (relationField.isAnnotationPresent(AssociationOverride.class))
        {
            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);
            JoinColumn[] joinColumns = annotation.joinColumns();

            relation.setJoinColumnName(joinColumns[0].name());

        }
        else if (isJoinedByFK)
        {
            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
            relation.setJoinColumnName(StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName()
                    : joinColumnAnn.name());
        }
        else
        {
            relation.setJoinColumnName(relationField.getName());
        }

        relation.setBiDirectionalField(metadata.getEntityClazz());
        metadata.addRelation(relationField.getName(), relation);

    }
1271564
public function assignRelated($source, $relationNames=null, $meta=null)
    {
        if (!$source) { return; }

        $stack = [];
        $sourceIsArray = is_array($source) || $source instanceof \Traversable;
        if (!$sourceIsArray) {
            $source = array($source);
        }

        if ($meta !== null) {
            $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta;
        } else {
            $meta = $this->mapper->getMeta(get_class($source[0]));
        }

        if (!$relationNames) {
            if ($meta->autoRelations) {
                $relationNames = $meta->autoRelations;
            } else {
                throw new Exception("relationNames not passed, class {$meta->class} does not define autoRelations");
            }
        }

        $relationMap = [];
        foreach ((array)$relationNames as $relationName) {
            if (!isset($meta->relations[$relationName])) {
                throw new Exception("Unknown relation $relationName on {$meta->class}");
            }
            $relationMap[$relationName] = $rel = $meta->relations[$relationName];
            if ($rel['mode'] == 'class') {
                throw new Exception("Relation $relationName is not assignable for class {$meta->class}");
            }
        }

        $done = [];
        foreach ($relationMap as $relationName=>$relation) {
            if (isset($done[$relationName])) {
                continue;
            }
            $done[$relationName] = true;

            $missing = [];
            foreach ($source as $idx=>$item) {
                // we have to assume it's missing if we see a getter as there
                // may be serious unintended side effects from calling a getter
                // that may be unpopulated. it might lazy load if it's an active
                // record, or it might throw an exception because the 'set' hasn't
                // been called.

                // check for isset as well as falsey for the situation where we're using
                // stdClasses as the response object
                if (isset($relation['getter']) || !isset($item->{$relationName}) || !$item->{$relationName}) {
                    $missing[$idx] = $item;
                }
            }

            if ($missing) {
                $result = $this->getRelated($missing, $relationName, ['stack'=>$stack], $meta);
                $relator = $this->getRelator($meta, $relationName);
                $this->populateObjectsWithRelated($missing, $result, $relation);
            }
        }
    }
956882
public void setPostMeta(final long postId, final List<Meta> postMeta) throws SQLException {

      clearPostMeta(postId);

      if(postMeta == null || postMeta.size() == 0) {
         return;
      }
      Connection conn = null;
      PreparedStatement stmt = null;
      Timer.Context ctx = metrics.setPostMetaTimer.time();
      try {
         conn = connectionSupplier.getConnection();
         stmt = conn.prepareStatement(insertPostMetaSQL);
         for(Meta meta : postMeta) {
            stmt.setLong(1, postId);
            stmt.setString(2, meta.key);
            stmt.setString(3, meta.value);
            stmt.executeUpdate();
         }
      } finally {
         ctx.stop();
         SQLUtil.closeQuietly(conn, stmt);
      }
   }
702758
public void setRelationalDatabaseEvents(java.util.Collection<RelationalDatabaseEvent> relationalDatabaseEvents) {
        if (relationalDatabaseEvents == null) {
            this.relationalDatabaseEvents = null;
            return;
        }

        this.relationalDatabaseEvents = new java.util.ArrayList<RelationalDatabaseEvent>(relationalDatabaseEvents);
    }
376967
@Override
    public final void setMetadataProperty(final String key, final String value) {
        _metadataProperties.put(key, value);
    }
108129
private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation,
            final EntityMetadata metadata, final PersistenceDelegator pd, boolean lazilyloaded,
            Map<Object, Object> relationStack)
    {
        final Object entityId = PropertyAccessorHelper.getId(entity, metadata);

        // if relation map contains value, then invoke target entity with find
        // by id.
        // else invoke target entity for find by relation, pass it's entityId as
        // a column value and relation.getJoinColumnName as column name.

        Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName(kunderaMetadata))
                : null;
        EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                relation.getTargetEntity());

        List relationalEntities = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata);

        if (relationalEntities != null)
        {

            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    addToRelationStack(relationStack, relationEntity, targetEntityMetadata);
                }
            }
            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    onParseRelation(entity, pd, targetEntityMetadata, relationEntity, relation, lazilyloaded,
                            relationStack);
                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,
                            PropertyAccessorHelper.getId(relationEntity, targetEntityMetadata));
                }
            }
        }

    }
250597
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());

        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());

        if (managedType.hasLobAttribute())
        {
            onPersistGFS(entity, id, entityMetadata, isUpdate);
        }

        else
        {
            Map<String, List<DBObject>> collections = new HashMap<String, List<DBObject>>();
            collections = onPersist(collections, entity, id, entityMetadata, rlHolders, isUpdate);
            onFlushCollection(collections);
        }
    }
1260978
public void markMetaDataColumns(ArrayList<String> metaDataColumns) {
		for (String column : metaDataColumns) {
			metaDataColumnsHashMap.put(column, column);
		}
	}
281539
@Override
    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)
    {
        // TODO: maxresults to be taken care after work on pagination.

        List<EnhanceEntity> ls = null;
        List<String> relationNames = m.getRelationNames();
        boolean isParent = m.isParent();
        if (!isParent)
        {
            // if it is not a parent.
            String sqlQuery = null;
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                sqlQuery = getSqlQueryFromJPA(m, relationNames, null);
            }
            else
            {
                // prepare lucene query and find.
                Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);
                if (rSet != null && !rSet.isEmpty())
                {
                    filter = "WHERE";
                }
                sqlQuery = getSqlQueryFromJPA(m, relationNames, rSet);
            }
            // call client with relation name list and convert to sql query.

            ls = populateEnhanceEntities(m, relationNames, client, sqlQuery);
        }
        else
        {
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                try
                {
                    List entities = ((HibernateClient) client).find(getSqlQueryFromJPA(m, relationNames, null),
                            new ArrayList<String>(), m);
                    ls = new ArrayList<EnhanceEntity>(entities.size());
                    ls = transform(m, ls, entities);
                }
                catch (Exception e)
                {
                    log.error("Error while executing handleAssociation for RDBMS, Caused by {}.", e);
                    throw new QueryHandlerException(e);
                }
            }
            else
            {
                ls = onAssociationUsingLucene(m, client, ls);
            }
        }

        return ls;
    }
1322116
function addRelationshipToModelMeta(modelName, property, meta) {
    if (!exports.relationshipsByModel[modelName]) {
        exports.relationshipsByModel[modelName] = {};
    }
    // TODO: investigate why we need to genericize to model (from <T>)
    exports.relationshipsByModel[modelName][property] = meta;
}
1269792
def update_metadata(self, loadbalancer, metadata, node=None):
        
        # Get the existing metadata
        md = self.get_metadata(loadbalancer, raw=True)
        id_lookup = dict([(itm["key"], itm["id"]) for itm in md])
        metadata_list = []
        # Updates must be done individually
        for key, val in metadata.items():
            try:
                meta_id = id_lookup[key]
                if node:
                    uri = "/loadbalancers/%s/nodes/%s/metadata/%s" % (
                            utils.get_id(loadbalancer), utils.get_id(node),
                            meta_id)
                else:
                    uri = "/loadbalancers/%s/metadata" % utils.get_id(loadbalancer)
                req_body = {"meta": {"value": val}}
                resp, body = self.api.method_put(uri, body=req_body)
            except KeyError:
                # Not an existing key; add to metadata_list
                metadata_list.append({"key": key, "value": val})
        if metadata_list:
            # New items; POST them
            if node:
                uri = "/loadbalancers/%s/nodes/%s/metadata" % (
                        utils.get_id(loadbalancer), utils.get_id(node))
            else:
                uri = "/loadbalancers/%s/metadata" % utils.get_id(loadbalancer)
            req_body = {"metadata": metadata_list}
            resp, body = self.api.method_post(uri, body=req_body)
898431
public void setDBIDs(DBIDs ids) {
    this.idrep.setDBIDs(ids);
    // Update relations.
    for (Relation<?> orel : this.relations) {
      if (orel instanceof ProxyView) {
        ((ProxyView<?>) orel).setDBIDs(this.idrep.getDBIDs());
      }
    }
  }
307336
private void populateRelations(EntityMetadata m, Object entity, Map<String, Object> relationMap, Node node,
            Map<Long, Object> nodeIdToEntityMap)
    {
        // Populate all relationship entities that are in Neo4J
        for (Relation relation : m.getRelations())
        {
            if (relation != null)
            {
                Class<?> targetEntityClass = relation.getTargetEntity();
                EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        targetEntityClass);
                Field property = relation.getProperty();
                if (relation.getPropertyType().isAssignableFrom(Map.class))
                {
                    Map<Object, Object> targetEntitiesMap = new HashMap<Object, Object>();

                    // If relationship entity is stored into Neo4J, fetch it
                    // immediately
                    if (isEntityForNeo4J(targetEntityMetadata))
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            if (relationship == null)
                            {
                                continue;
                            }

                            // Target Entity
                            Node endNode = relationship.getEndNode();
                            if (endNode == null)
                            {
                                continue;
                            }
                            Object targetEntity = nodeIdToEntityMap.get(endNode.getId());
                            if (targetEntity == null)
                            {
                                targetEntity = mapper.getEntityFromNode(endNode, targetEntityMetadata);
                            }

                            // Relationship Entity
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            // If this relationship is bidirectional, put source
                            // entity into Map field for target entity
                            Field bidirectionalField = relation.getBiDirectionalField();
                            Map<Object, Object> sourceEntitiesMap = new HashMap<Object, Object>();
                            if (bidirectionalField != null)
                            {
                                for (Relationship incomingRelationship : endNode.getRelationships(Direction.INCOMING,
                                        DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                                {
                                    Node startNode = incomingRelationship.getStartNode();
                                    Object sourceEntity = nodeIdToEntityMap.get(startNode.getId());
                                    if (sourceEntity == null)
                                    {
                                        sourceEntity = mapper.getEntityFromNode(startNode, m);
                                        nodeIdToEntityMap.put(startNode.getId(), sourceEntity);
                                    }
                                    sourceEntitiesMap.put(relationshipEntity, sourceEntity);
                                }
                                PropertyAccessorHelper.set(targetEntity, bidirectionalField, sourceEntitiesMap);
                            }

                            // Set references to Target and owning entity in
                            // relationship entity
                            Class<?> relationshipClass = relation.getMapKeyJoinClass();
                            for (Field f : relationshipClass.getDeclaredFields())
                            {
                                if (!ReflectUtils.isTransientOrStatic(f))
                                {

                                    if (f.getType().equals(m.getEntityClazz()))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, entity);
                                    }
                                    else if (f.getType().equals(targetEntityClass))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, targetEntity);
                                    }
                                }
                            }
                            targetEntitiesMap.put(relationshipEntity, targetEntity);
                        }

                        PropertyAccessorHelper.set(entity, property, targetEntitiesMap);
                    }

                    /**
                     * If relationship entity is stored in a database other than
                     * Neo4J foreign keys are stored in "Proxy Nodes", retrieve
                     * these foreign keys and set into EnhanceEntity
                     */
                    else
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            Node proxyNode = relationship.getEndNode();

                            String targetEntityIdColumnName = ((AbstractAttribute) targetEntityMetadata
                                    .getIdAttribute()).getJPAColumnName();
                            Object targetObjectId = proxyNode.getProperty(targetEntityIdColumnName);
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            targetEntitiesMap.put(targetObjectId, relationshipEntity);
                        }

                        relationMap.put(relation.getJoinColumnName(kunderaMetadata), targetEntitiesMap);
                    }
                }
            }
        }
    }
155105
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        try
        {
            Map<String, Object> values = new HashMap<String, Object>();

            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(entityMetadata.getPersistenceUnit());

            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());

            String keyAsString = getKeyAsString(id, entityMetadata, metaModel);

            addSource(entity, values, entityType);

            addRelations(rlHolders, values);
            addDiscriminator(values, entityType);

            IndexResponse response = txClient
                    .prepareIndex(entityMetadata.getSchema().toLowerCase(), entityMetadata.getTableName(), keyAsString)
                    .setSource(values).setRefresh(isRefreshIndexes()).execute().actionGet();

            assert response.getId() != null;
        }
        finally
        {
            // Nothing as of now.
        }

    }