Compute the appropriate namer for the Java field marked by @ManyToOne

@param fromAttribute     the column that is the foreign key.
@param targetEntityNamer the default namer for the entity on the other side of the relation.
485326
public Namer getManyToOneNamer(Attribute fromAttribute, Namer targetEntityNamer) {
        // configuration
        Namer result = getManyToOneNamerFromConf(fromAttribute.getColumnConfig(), targetEntityNamer);

        // fall back
        if (result == null) {
            result = getXToOneNamerFallBack(fromAttribute, targetEntityNamer);
        }

        return result;
    }
633688
public Attribute getEntityAttribute(Class clazz, String fieldName)
    {
        if (entityTypes != null && entityTypes.containsKey(clazz))
        {
            EntityType entityType = entityTypes.get(clazz);
            return entityType.getAttribute(fieldName);
        }
        throw new IllegalArgumentException("No entity found: " + clazz);
    }
540094
@SuppressWarnings("unchecked")
    public T fromDMR(String keyValue, ModelNode modelNode) throws Exception {

        if (isBaseTypeAdapter()) return convertToBaseType(modelNode);

        ModelNode actualPayload = null;

        if (ModelType.OBJECT.equals(modelNode.getType())) {
            actualPayload = modelNode;
        }
       /* else if(ModelType.PROPERTY.equals(modelNode.getType()))
        {
            final Property property = modelNode.asProperty();
            actualPayload = property.getValue();
        }*/
        else {
            throw new IllegalArgumentException("Unsupported ModelType " + modelNode.getType() + ": " + modelNode);
        }

        ClassInfo clazz = index.getClassByName(DotName.createSimple(getType().getCanonicalName()));

        T entity = null;
        boolean implicitKey = clazz.annotations().containsKey(IndexFactory.IMPLICIT_META);

        if (implicitKey) {
            // implicit (aka singleton) resource
            Constructor<?> ctor = getType().getConstructor();
            entity = (T) ctor.newInstance();
        } else {
            // explicit (regular) resource
            entity = (T) getType().getConstructor(String.class)
                    .newInstance(keyValue);
        }


        for (MethodInfo method : clazz.methods()) {
            if (method.hasAnnotation(IndexFactory.BINDING_META)) {

                Method getter = entity.getClass().getMethod(method.name());
                Class<?> propertyType = getter.getReturnType();

                ModelNodeBinding binding = getter.getDeclaredAnnotation(ModelNodeBinding.class);
                String detypedName = binding.detypedName();

                ModelNode dmrPayload = actualPayload.get(detypedName);


                // EXPRESSIONS
                if(ModelType.EXPRESSION == dmrPayload.getType()) {

                    ValueExpression expression = dmrPayload.asExpression();

                    ((Map)entity).put(method.name(), expression.getExpressionString());

                    continue; // expression have precedence over real values

                }


                // VALUES
                ModelType dmrType = Types.resolveModelType(propertyType);
                if (dmrType == ModelType.LIST) {
                    new ListTypeAdapter().fromDmr(entity, method.name(), dmrType, propertyType, dmrPayload);
                } else if (dmrType == ModelType.OBJECT) {
                    new MapTypeAdapter().fromDmr(entity, method.name(), dmrType, propertyType, dmrPayload);
                } else {
                    new SimpleTypeAdapter().fromDmr(entity, method.name(), dmrType, propertyType, dmrPayload);
                }


            }
        }
        return entity;
    }
615255
private Set<Resource> fetchRelationFromEntity(IncludeRequest request, List<Resource> sourceResources, ResourceField
			relationshipField, boolean allowLookup, boolean fetchRelatedEntity, boolean mustInclude) {
		Set<Resource> loadedResources = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object sourceEntity = request.getEntity(id);
			if (sourceEntity != null && !(sourceEntity instanceof Resource)) {

				Object relatedEntity = null;
				if (fetchRelatedEntity) {
					relatedEntity = relationshipField.getAccessor().getValue(sourceEntity);
					if (!allowLookup && Iterable.class.isAssignableFrom(relationshipField.getType()) && relatedEntity == null) {
						// note that single-valued relations are allowed to be null
						throw new InternalServerErrorException(
								id + " relationship field collection '" + relationshipField.getJsonName()
										+ "' can not be null. Either set the relationship as an empty "
										+ Iterable.class.getCanonicalName() + " or use LookupIncludeBehavior.AUTOMATICALLY_ALWAYS");
					}
				}

				// attempt to work with full relationship and fallback to relationshipId where possible
				if (relatedEntity != null) {
					List<Resource> relatedResources =
							request.setupRelation(sourceResource, relationshipField, relatedEntity);
					loadedResources.addAll(relatedResources);
				} else if (relationshipField.hasIdField()) {
					Object relatedEntityID = relationshipField.getIdAccessor().getValue(sourceEntity);
					request.setupRelationId(sourceResource, relationshipField, relatedEntityID);
					if (fetchRelatedEntity && relatedEntityID != null && !allowLookup && mustInclude) {
						throw new IllegalStateException("inconsistent relationship '" + relationshipField.getUnderlyingName()
								+ "' for " + id + ", id "
								+ "set to " + relatedEntityID + ", but related object is null and lookup disabled");
					}
				}
			}
		}
		return loadedResources;
	}
1221308
protected function fromArrayRelationEntity($v, $p, $pn, $getter, $setter,
                                                $association, $policy,
                                                Reader $ar,
                                                PolicyResolver $pr,
                                                EntityManagerInterface $em,
                                                \ReflectionClass $refClass,
                                                $idField, $class, $subPolicy) {
        $jc = $ar->getPropertyAnnotation($p, 'Doctrine\ORM\Mapping\JoinColumn'); // find target id field name
        if($jc) { $idField = $jc->referencedColumnName; }
        $idGetter = 'get'.ucfirst($idField);  
                        
        $subEntity = null;
        
         // non-existent
        if(empty($v[$idField])) {
            if($policy instanceof Policy\Interfaces\DenyNewFrom) { return; }
            $subEntity = new $class();
            $subEntity->fromArray($v, $em, $subPolicy, $ar, $pr);
            $this->$setter($subEntity);
            
        // existent
        } else {
            $current = $this->$getter();
            
            // existent internal
            if($current && ($current->$idGetter() === $v[$idField])) { 
                $subEntity = $current;
                
            // RETRIEVING existent external
            } else if(!($policy instanceof Policy\Interfaces\DenyUpdateFrom) || $policy->allowExternal) { 
                $subEntity = $em->getReference($class, $v[$idField]);
            }
            
            // UPDATING internal or external
            if($subEntity) {
                if(!($policy instanceof Policy\Interfaces\DenyUpdateFrom) || $policy->allowExistent) {
                    $subEntity->fromArray($v, $em, $subPolicy, $ar, $pr);
                }
                $this->$setter($subEntity);
            }
            
        }
    }
505183
public AttributeMapping addAttributeMapping(String targetAttributeName) {
    if (attributeMappings.containsKey(targetAttributeName)) {
      throw new IllegalStateException(
          "AttributeMapping already exists for target attribute " + targetAttributeName);
    }
    Attribute targetAttribute = targetEntityType.getAttribute(targetAttributeName);
    AttributeMapping attributeMapping = new AttributeMapping(targetAttribute);
    attributeMappings.put(targetAttributeName, attributeMapping);
    return attributeMapping;
  }
1360659
public static String getMappedName(EntityMetadata parentMetadata, Relation relation,
            final KunderaMetadata kunderaMetadata)
    {
        if (relation != null)
        {
            String joinColumn = relation.getJoinColumnName(kunderaMetadata);
            if (joinColumn == null)
            {
                Class clazz = relation.getTargetEntity();
                EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);

                joinColumn = relation.getType().equals(ForeignKey.ONE_TO_MANY) ? ((AbstractAttribute) parentMetadata
                        .getIdAttribute()).getJPAColumnName() : ((AbstractAttribute) metadata.getIdAttribute())
                        .getJPAColumnName();
            }
            return joinColumn;
        }
        return null;
    }
1089295
public void populateRelationshipProperties(EntityMetadata entityMetadata, EntityMetadata targetNodeMetadata,
            Relationship relationship, Object relationshipObj)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        EntityType entityType = metaModel.entity(relationshipObj.getClass());

        Set<Attribute> attributes = entityType.getSingularAttributes();
        for (Attribute attribute : attributes)
        {
            Field f = (Field) attribute.getJavaMember();
            if (!f.getType().equals(entityMetadata.getEntityClazz())
                    && !f.getType().equals(targetNodeMetadata.getEntityClazz()))
            {
                EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        relationshipObj.getClass());
                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                if (metaModel.isEmbeddable(relMetadata.getIdAttribute().getBindableJavaType())
                        && ((SingularAttribute) attribute).isId())
                {
                    // Populate Embedded attribute value into relationship
                    Object id = PropertyAccessorHelper.getId(relationshipObj, relMetadata);
                    Object serializedIdValue = serializeIdAttributeValue(relMetadata, metaModel, id);
                    relationship.setProperty(columnName, serializedIdValue);

                    // Populate attributes of embedded fields into relationship
                    Set<Attribute> embeddableAttributes = metaModel.embeddable(
                            relMetadata.getIdAttribute().getBindableJavaType()).getSingularAttributes();
                    for (Attribute embeddableAttribute : embeddableAttributes)
                    {
                        String embeddedColumn = ((AbstractAttribute) embeddableAttribute).getJPAColumnName();
                        if (embeddedColumn == null)
                            embeddedColumn = embeddableAttribute.getName();
                        Object value = PropertyAccessorHelper
                                .getObject(id, (Field) embeddableAttribute.getJavaMember());

                        if (value != null)
                            relationship.setProperty(embeddedColumn, value);
                    }
                }
                else
                {
                    Object value = PropertyAccessorHelper.getObject(relationshipObj, f);
                    relationship.setProperty(columnName, toNeo4JProperty(value));
                }

            }
        }

    }
687846
public Namer getOneToManyNamer(ColumnConfig fromAttributeColumnConfig, Namer fromEntityNamer) {
        // configuration
        Namer result = getOneToManyNamerFromConf(fromAttributeColumnConfig.getOneToManyConfig(), fromEntityNamer);

        // convention
        if (result == null) {
            result = fromEntityNamer;
        }

        return result;
    }
821732
public void init(BaseField field, String targetFieldName, BaseField fldTarget)
    {
        super.init(field);

        m_bDisableTarget = false;
        this.targetFieldName = targetFieldName;
        m_fldTarget = fldTarget;
    }
22536
protected void registerIfNamed(Class<?> from, Serializer<?> serializer)
	{
		if(from.isAnnotationPresent(Named.class))
		{
			Named named = from.getAnnotation(Named.class);
			QualifiedName key = new QualifiedName(named.namespace(), named.name());
			nameToSerializer.put(key, serializer);
			serializerToName.put(serializer, key);
		}
	}
767816
public function joinTableName($sourceEntity, $targetEntity, $propertyName = null)
    {
        $names = [
            $this->classToFieldName($sourceEntity),
            $this->classToFieldName($targetEntity)
        ];

        sort($names);

        return implode('_', $names);
    }
1314846
public void assignField(ConnectionSource connectionSource, Object data, Object val, boolean parentObject,
			ObjectCache objectCache) throws SQLException {

		if (logger.isLevelEnabled(Level.TRACE)) {
			logger.trace("assiging from data {}, val {}: {}", (data == null ? "null" : data.getClass()),
					(val == null ? "null" : val.getClass()), val);
		}
		// if this is a foreign object then val is the foreign object's id val
		if (foreignRefField != null && val != null) {
			// get the current field value which is the foreign-id
			Object foreignRef = extractJavaFieldValue(data);
			/*
			 * See if we don't need to create a new foreign object. If we are refreshing and the id field has not
			 * changed then there is no need to create a new foreign object and maybe lose previously refreshed field
			 * information.
			 */
			if (foreignRef != null && foreignRef.equals(val)) {
				return;
			}
			// awhitlock: raised as OrmLite issue: bug #122
			Object cachedVal;
			ObjectCache foreignCache = foreignDao.getObjectCache();
			if (foreignCache == null) {
				cachedVal = null;
			} else {
				cachedVal = foreignCache.get(getType(), val);
			}
			if (cachedVal != null) {
				val = cachedVal;
			} else if (!parentObject) {
				// the value we are to assign to our field is now the foreign object itself
				val = createForeignObject(connectionSource, val, objectCache);
			}
		}

		if (fieldSetMethod == null) {
			try {
				field.set(data, val);
			} catch (IllegalArgumentException e) {
				if (val == null) {
					throw SqlExceptionUtil.create("Could not assign object '" + val + "' to field " + this, e);
				} else {
					throw SqlExceptionUtil.create(
							"Could not assign object '" + val + "' of type " + val.getClass() + " to field " + this, e);
				}
			} catch (IllegalAccessException e) {
				throw SqlExceptionUtil.create(
						"Could not assign object '" + val + "' of type " + val.getClass() + "' to field " + this, e);
			}
		} else {
			try {
				fieldSetMethod.invoke(data, val);
			} catch (Exception e) {
				throw SqlExceptionUtil
						.create("Could not call " + fieldSetMethod + " on object with '" + val + "' for " + this, e);
			}
		}
	}
343607
private String getTargetEntity(List<? extends AnnotationMirror> annotations) {
		String fullyQualifiedTargetEntityName = null;
		for ( AnnotationMirror mirror : annotations ) {
			if ( TypeUtils.isAnnotationMirrorOfType( mirror, Constants.ELEMENT_COLLECTION ) ) {
				fullyQualifiedTargetEntityName = getFullyQualifiedClassNameOfTargetEntity( mirror, "targetClass" );
			}
			else if ( TypeUtils.isAnnotationMirrorOfType( mirror, Constants.ONE_TO_MANY )
					|| TypeUtils.isAnnotationMirrorOfType( mirror, Constants.MANY_TO_MANY )
					|| TypeUtils.isAnnotationMirrorOfType( mirror, Constants.MANY_TO_ONE )
					|| TypeUtils.isAnnotationMirrorOfType( mirror, Constants.ONE_TO_ONE ) ) {
				fullyQualifiedTargetEntityName = getFullyQualifiedClassNameOfTargetEntity( mirror, "targetEntity" );
			}
			else if ( TypeUtils.isAnnotationMirrorOfType( mirror, ORG_HIBERNATE_ANNOTATIONS_TARGET ) ) {
				fullyQualifiedTargetEntityName = getFullyQualifiedClassNameOfTargetEntity( mirror, "value" );
			}
		}
		return fullyQualifiedTargetEntityName;
	}
1358625
Set<AttributeDescriptor> mappedAttributes(EntityDescriptor entity,
                                              AttributeDescriptor attribute,
                                              EntityDescriptor referenced) {
        String mappedBy = attribute.mappedBy();
        if (Names.isEmpty(mappedBy)) {
            return referenced.attributes().stream()
                .filter(other -> other.cardinality() != null)
                .filter(other -> referencingEntity(other).isPresent())
                .filter(other -> referencingEntity(other)
                        .orElseThrow(IllegalStateException::new) == entity)
                .collect(Collectors.toSet());
        } else {
            return referenced.attributes().stream()
                .filter(other -> other.name().equals(mappedBy))
                .collect(Collectors.toSet());
        }
    }
91063
public void setTargetName (String targetName) {
        if (targetName == null) target = null;
        target = targetServer.getTarget(targetName);
    }
1163439
private String getRefSQL(ForeignKeyConstraint fk) {

		Set<Object> columns = new LinkedHashSet<>(); // Set avoids duplicated and LinkedHashSet keeps the insertion order
		for (Attribute attr : getIdentifyingAttributes(fk.getRelation()))
			columns.add(getColumnNameWithAlias(attr));

		List<String> conditions = new ArrayList<>(fk.getComponents().size());
		for (ForeignKeyConstraint.Component comp : fk.getComponents()) {
			columns.add(getColumnNameWithAlias(comp.getReference()));	
			conditions.add(getColumnName(comp.getAttribute()) + " = " + getColumnName(comp.getReference()));
		}
		
		for (Attribute attr : getIdentifyingAttributes(fk.getReferencedRelation())) 
			columns.add(getColumnNameWithAlias(attr));

		final String tables = fk.getRelation().getID().getSQLRendering() + 
							", " + fk.getReferencedRelation().getID().getSQLRendering();
		
		return String.format("SELECT %s FROM %s WHERE %s", 
				Joiner.on(", ").join(columns), tables, Joiner.on(" AND ").join(conditions));
	}