Search in sources :

Example 1 with ForeignReferenceMapping

use of org.eclipse.persistence.mappings.ForeignReferenceMapping in project eclipselink by eclipse-ee4j.

the class MappingAccessor method setIndirectionPolicy.

/**
 * INTERNAL:
 * Set the correct indirection policy on a collection mapping. Method
 * assume that the reference class has been set on the mapping before
 * calling this method.
 */
protected void setIndirectionPolicy(ContainerMapping mapping, String mapKey, boolean usesIndirection) {
    MetadataClass rawClass = getRawClass();
    boolean containerPolicySet = false;
    if (usesIndirection && (mapping instanceof ForeignReferenceMapping)) {
        containerPolicySet = true;
        CollectionMapping collectionMapping = (CollectionMapping) mapping;
        if (rawClass.isClass(Map.class)) {
            if (collectionMapping.isDirectMapMapping()) {
                ((DirectMapMapping) mapping).useTransparentMap();
            } else {
                collectionMapping.useTransparentMap(mapKey);
            }
        } else if (rawClass.isClass(List.class)) {
            collectionMapping.useTransparentList();
        } else if (rawClass.isClass(Collection.class)) {
            collectionMapping.useTransparentCollection();
        } else if (rawClass.isClass(Set.class)) {
            collectionMapping.useTransparentSet();
        } else {
            getLogger().logWarningMessage(MetadataLogger.WARNING_INVALID_COLLECTION_USED_ON_LAZY_RELATION, getJavaClass(), getAnnotatedElement(), rawClass);
            processIndirection((ForeignReferenceMapping) mapping);
            containerPolicySet = false;
        }
    } else {
        if (mapping instanceof CollectionMapping) {
            ((CollectionMapping) mapping).dontUseIndirection();
        }
    }
    if (!containerPolicySet) {
        if (rawClass.isClass(Map.class)) {
            if (mapping instanceof DirectMapMapping) {
                ((DirectMapMapping) mapping).useMapClass(java.util.Hashtable.class);
            } else {
                mapping.useMapClass(java.util.Hashtable.class, mapKey);
            }
        } else if (rawClass.isClass(Set.class)) {
            // This will cause it to use a CollectionContainerPolicy type
            mapping.useCollectionClass(java.util.HashSet.class);
        } else if (rawClass.isClass(List.class)) {
            // This will cause a ListContainerPolicy type to be used or
            // OrderedListContainerPolicy if ordering is specified.
            mapping.useCollectionClass(java.util.Vector.class);
        } else if (rawClass.isClass(Collection.class)) {
            // Force CollectionContainerPolicy type to be used with a
            // collection implementation.
            mapping.setContainerPolicy(new CollectionContainerPolicy(java.util.Vector.class));
        } else {
            // Use the supplied collection class type if its not an interface
            if (mapKey == null || mapKey.equals("")) {
                if (rawClass.isList()) {
                    mapping.useListClassName(rawClass.getName());
                } else {
                    mapping.useCollectionClassName(rawClass.getName());
                }
            } else {
                mapping.useMapClassName(rawClass.getName(), mapKey);
            }
        }
    }
}
Also used : ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) CollectionContainerPolicy(org.eclipse.persistence.internal.queries.CollectionContainerPolicy) Set(java.util.Set) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CollectionMapping(org.eclipse.persistence.mappings.CollectionMapping) DirectMapMapping(org.eclipse.persistence.mappings.DirectMapMapping)

Example 2 with ForeignReferenceMapping

use of org.eclipse.persistence.mappings.ForeignReferenceMapping in project eclipselink by eclipse-ee4j.

the class PersistenceContext method setRelationshipInfo.

private void setRelationshipInfo(Object entity) {
    if ((entity != null) && (entity instanceof PersistenceWeavedRest)) {
        ClassDescriptor descriptor = getServerSession().getClassDescriptor(entity.getClass());
        if (descriptor != null) {
            ((PersistenceWeavedRest) entity)._persistence_setRelationships(new ArrayList<>());
            for (DatabaseMapping mapping : descriptor.getMappings()) {
                if (mapping.isForeignReferenceMapping()) {
                    ForeignReferenceMapping frMapping = (ForeignReferenceMapping) mapping;
                    RelationshipInfo info = new RelationshipInfo();
                    info.setAttributeName(frMapping.getAttributeName());
                    info.setOwningEntity(entity);
                    info.setOwningEntityAlias(descriptor.getAlias());
                    info.setPersistencePrimaryKey(descriptor.getObjectBuilder().extractPrimaryKeyFromObject(entity, (AbstractSession) getServerSession()));
                    ((PersistenceWeavedRest) entity)._persistence_getRelationships().add(info);
                } else if (mapping.isEISMapping()) {
                    if (mapping instanceof EISCompositeCollectionMapping) {
                        EISCompositeCollectionMapping eisMapping = (EISCompositeCollectionMapping) mapping;
                        RelationshipInfo info = new RelationshipInfo();
                        info.setAttributeName(eisMapping.getAttributeName());
                        info.setOwningEntity(entity);
                        info.setOwningEntityAlias(descriptor.getAlias());
                        info.setPersistencePrimaryKey(descriptor.getObjectBuilder().extractPrimaryKeyFromObject(entity, (AbstractSession) getServerSession()));
                        ((PersistenceWeavedRest) entity)._persistence_getRelationships().add(info);
                    }
                }
            }
        }
    }
}
Also used : ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) RelationshipInfo(org.eclipse.persistence.internal.jpa.rs.weaving.RelationshipInfo) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) PersistenceWeavedRest(org.eclipse.persistence.internal.jpa.rs.weaving.PersistenceWeavedRest) EISCompositeCollectionMapping(org.eclipse.persistence.eis.mappings.EISCompositeCollectionMapping) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 3 with ForeignReferenceMapping

use of org.eclipse.persistence.mappings.ForeignReferenceMapping in project eclipselink by eclipse-ee4j.

the class MappingAccessor method processMapKeyClass.

/**
 * INTERNAL:
 * Process a map key class for the given map key map accessor.
 */
protected void processMapKeyClass(ContainerMapping mapping, MappedKeyMapAccessor mappedKeyMapAccessor) {
    MapKeyMapping keyMapping;
    MetadataClass mapKeyClass = mappedKeyMapAccessor.getMapKeyClass();
    if (getProject().hasEntity(mapKeyClass)) {
        keyMapping = processEntityMapKeyClass(mappedKeyMapAccessor);
    } else if (getProject().hasEmbeddable(mapKeyClass)) {
        keyMapping = processEmbeddableMapKeyClass(mappedKeyMapAccessor);
    } else {
        keyMapping = processDirectMapKeyClass(mappedKeyMapAccessor);
    }
    Class<?> containerClass;
    if (mapping instanceof ForeignReferenceMapping) {
        if (usesIndirection()) {
            containerClass = ClassConstants.IndirectMap_Class;
            ((ForeignReferenceMapping) mapping).setIndirectionPolicy(new TransparentIndirectionPolicy());
        } else {
            containerClass = java.util.Hashtable.class;
            ((ForeignReferenceMapping) mapping).dontUseIndirection();
        }
    } else {
        containerClass = java.util.Hashtable.class;
    }
    MappedKeyMapContainerPolicy policy = new MappedKeyMapContainerPolicy(containerClass);
    policy.setKeyMapping(keyMapping);
    policy.setValueMapping((MapComponentMapping) mapping);
    mapping.setContainerPolicy(policy);
}
Also used : ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) TransparentIndirectionPolicy(org.eclipse.persistence.internal.indirection.TransparentIndirectionPolicy) MetadataClass(org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass) MapKeyMapping(org.eclipse.persistence.mappings.foundation.MapKeyMapping) MappedKeyMapContainerPolicy(org.eclipse.persistence.internal.queries.MappedKeyMapContainerPolicy)

Example 4 with ForeignReferenceMapping

use of org.eclipse.persistence.mappings.ForeignReferenceMapping in project eclipselink by eclipse-ee4j.

the class AbstractEntityResource method checkIdempotenceOnRelationships.

/**
 * This method maintains idempotence on PUT by disallowing sequencing in relationships.
 *
 * @param descriptor    descriptor of the entity passed in 'entity' parameter.
 * @param entity        entity to process.
 * @return true if check is passed (no sequencing)
 */
private boolean checkIdempotenceOnRelationships(ClassDescriptor descriptor, Object entity) {
    final List<DatabaseMapping> mappings = descriptor.getMappings();
    if ((mappings != null) && (!mappings.isEmpty())) {
        for (DatabaseMapping mapping : mappings) {
            if (mapping instanceof ForeignReferenceMapping) {
                final ForeignReferenceMapping fkMapping = (ForeignReferenceMapping) mapping;
                if ((fkMapping.isCascadePersist()) || (fkMapping.isCascadeMerge())) {
                    final ClassDescriptor referenceDescriptor = fkMapping.getReferenceDescriptor();
                    if (referenceDescriptor != null) {
                        if (referenceDescriptor instanceof RelationalDescriptor) {
                            final RelationalDescriptor relDesc = (RelationalDescriptor) referenceDescriptor;
                            final AbstractDirectMapping relSequenceMapping = relDesc.getObjectBuilder().getSequenceMapping();
                            if (relSequenceMapping != null) {
                                final Object value = mapping.getAttributeAccessor().getAttributeValueFromObject(entity);
                                if (value != null) {
                                    if (value instanceof ValueHolder) {
                                        final ValueHolder<?> holder = (ValueHolder<?>) value;
                                        if (holder.getValue() != null) {
                                            return false;
                                        }
                                    } else if (value instanceof Collection) {
                                        if (!(((Collection<?>) value).isEmpty())) {
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return true;
}
Also used : RelationalDescriptor(org.eclipse.persistence.descriptors.RelationalDescriptor) ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) AbstractDirectMapping(org.eclipse.persistence.mappings.foundation.AbstractDirectMapping) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) Collection(java.util.Collection) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) ValueHolder(org.eclipse.persistence.indirection.ValueHolder)

Example 5 with ForeignReferenceMapping

use of org.eclipse.persistence.mappings.ForeignReferenceMapping in project eclipselink by eclipse-ee4j.

the class AbstractEntityResource method findAttributeInternal.

protected Response findAttributeInternal(String version, String persistenceUnit, String type, String id, String attribute, HttpHeaders headers, UriInfo uriInfo) {
    JPARSLogger.entering(CLASS_NAME, "findAttributeInternal", new Object[] { "GET", version, persistenceUnit, type, id, attribute, uriInfo.getRequestUri().toASCIIString() });
    EntityManager em = null;
    try {
        PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
        Object entityId = IdHelper.buildId(context, type, id);
        em = context.getEmf().createEntityManager(getMatrixParameters(uriInfo, persistenceUnit));
        Object entity = em.find(context.getClass(type), entityId, getQueryParameters(uriInfo));
        DatabaseSession serverSession = context.getServerSession();
        ClassDescriptor descriptor = serverSession.getClassDescriptor(context.getClass(type));
        if (descriptor == null) {
            throw JPARSException.classOrClassDescriptorCouldNotBeFoundForEntity(type, persistenceUnit);
        }
        DatabaseMapping attributeMapping = descriptor.getMappingForAttributeName(attribute);
        if ((attributeMapping == null) || (entity == null)) {
            throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
        }
        if (!attributeMapping.isCollectionMapping()) {
            Object result = attributeMapping.getRealAttributeValueFromAttribute(attributeMapping.getAttributeValueFromObject(entity), entity, (AbstractSession) serverSession);
            if (result == null) {
                JPARSLogger.error(context.getSessionLog(), "jpars_could_not_find_entity_for_attribute", new Object[] { attribute, type, id, persistenceUnit });
                throw JPARSException.attributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
            }
            final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
            return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, null);
        }
        ReadQuery query = (ReadQuery) ((((ForeignReferenceMapping) attributeMapping).getSelectionQuery()).clone());
        if (query == null) {
            throw JPARSException.selectionQueryForAttributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
        }
        final FeatureSet featureSet = context.getSupportedFeatureSet();
        final AbstractSession clientSession = context.getClientSession(em);
        // Fields filtering
        FieldsFilter fieldsFilter = null;
        if (context.getSupportedFeatureSet().isSupported(Feature.FIELDS_FILTERING)) {
            final FieldsFilteringValidator fieldsFilteringValidator = new FieldsFilteringValidator(uriInfo);
            if (fieldsFilteringValidator.isFeatureApplicable()) {
                fieldsFilter = fieldsFilteringValidator.getFilter();
            }
        }
        // Pagination
        if (featureSet.isSupported(Feature.PAGING)) {
            final PageableFieldValidator validator = new PageableFieldValidator(entity.getClass(), attribute, uriInfo);
            if (validator.isFeatureApplicable()) {
                // Adding extra one to detect are there more rows or not. It will be removed later
                // on in response processor.
                query.setMaxRows(validator.getLimit() + validator.getOffset() + 1);
                query.setFirstResult(validator.getOffset());
                // We need to add limit and offset to query parameters because request builder reads it from there
                final Map<String, Object> queryParams = getQueryParameters(uriInfo);
                queryParams.put(QueryParameters.JPARS_PAGING_LIMIT, String.valueOf(validator.getLimit()));
                queryParams.put(QueryParameters.JPARS_PAGING_OFFSET, String.valueOf(validator.getOffset()));
                // check orderBy, and generate a warning if there is none
                checkOrderBy(context, query);
                final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
                final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.PAGING);
                return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, queryParams, headers, uriInfo, responseBuilder, fieldsFilter);
            }
        }
        final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
        final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
        return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, fieldsFilter);
    } catch (Exception ex) {
        throw JPARSException.exceptionOccurred(ex);
    } finally {
        if (em != null) {
            if (em.isOpen()) {
                em.close();
            }
        }
    }
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseSession(org.eclipse.persistence.sessions.DatabaseSession) PersistenceContext(org.eclipse.persistence.jpa.rs.PersistenceContext) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) FieldsFilteringValidator(org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilteringValidator) JPARSException(org.eclipse.persistence.jpa.rs.exceptions.JPARSException) PageableFieldValidator(org.eclipse.persistence.jpa.rs.features.paging.PageableFieldValidator) FeatureResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder) EntityManager(jakarta.persistence.EntityManager) ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) FieldsFilter(org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilter) FeatureSet(org.eclipse.persistence.jpa.rs.features.FeatureSet) ReadQuery(org.eclipse.persistence.queries.ReadQuery) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Aggregations

ForeignReferenceMapping (org.eclipse.persistence.mappings.ForeignReferenceMapping)50 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)29 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)20 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)8 ArrayList (java.util.ArrayList)7 ValueHolder (org.eclipse.persistence.indirection.ValueHolder)5 ObjectExpression (org.eclipse.persistence.internal.expressions.ObjectExpression)5 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)5 Collection (java.util.Collection)4 Map (java.util.Map)4 BasicIndirectionPolicy (org.eclipse.persistence.internal.indirection.BasicIndirectionPolicy)4 MetadataClass (org.eclipse.persistence.internal.jpa.metadata.accessors.objects.MetadataClass)4 EntityManager (jakarta.persistence.EntityManager)3 Method (java.lang.reflect.Method)3 HashMap (java.util.HashMap)3 Expression (org.eclipse.persistence.expressions.Expression)3 QueryKeyExpression (org.eclipse.persistence.internal.expressions.QueryKeyExpression)3 InvalidObject (org.eclipse.persistence.internal.helper.InvalidObject)3 TransparentIndirectionPolicy (org.eclipse.persistence.internal.indirection.TransparentIndirectionPolicy)3 FetchGroup (org.eclipse.persistence.queries.FetchGroup)3