Search in sources :

Example 6 with ObjectReferenceMapping

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

the class CacheableModelJunitTest method testUpdateForceProtectedOneToOne.

public void testUpdateForceProtectedOneToOne() {
    EntityManager em = createDSEntityManager();
    beginTransaction(em);
    int cfeID = 0;
    try {
        CacheableForceProtectedEntity cte = em.find(CacheableForceProtectedEntity.class, m_cacheableForceProtectedEntity1Id);
        CacheableFalseEntity oldcfe = cte.getCacheableFalse();
        ServerSession session = em.unwrap(ServerSession.class);
        CacheableFalseEntity cfe = new CacheableFalseEntity();
        em.persist(cfe);
        cfeID = cfe.getId();
        cte.setCacheableFalse(cfe);
        commitTransaction(em);
        CacheableForceProtectedEntity cachedCPE = (CacheableForceProtectedEntity) session.getIdentityMapAccessor().getFromIdentityMap(cte);
        assertNull("A protected OneToOne relationship was merged into the shared cache", cachedCPE.getCacheableFalse());
        ObjectReferenceMapping orm = (ObjectReferenceMapping) session.getDescriptor(CacheableForceProtectedEntity.class).getMappingForAttributeName("cacheableFalse");
        Object cacheableFalsefk = session.getIdentityMapAccessorInstance().getCacheKeyForObject(cte).getProtectedForeignKeys().get(orm.getSelectFields().get(0));
        assertEquals("FK update not cached", cfe.getId(), cacheableFalsefk);
        beginTransaction(em);
        cte.setCacheableFalse(oldcfe);
        cfe = em.find(CacheableFalseEntity.class, cfeID);
        em.remove(cfe);
        commitTransaction(em);
    } finally {
        if (isTransactionActive(em)) {
            rollbackTransaction(em);
        }
        closeEM(em);
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) ServerSession(org.eclipse.persistence.sessions.server.ServerSession) ObjectReferenceMapping(org.eclipse.persistence.mappings.ObjectReferenceMapping) CacheableForceProtectedEntity(org.eclipse.persistence.testing.models.jpa.cacheable.CacheableForceProtectedEntity) CacheableFalseEntity(org.eclipse.persistence.testing.models.jpa.cacheable.CacheableFalseEntity) ChildCacheableFalseEntity(org.eclipse.persistence.testing.models.jpa.cacheable.ChildCacheableFalseEntity)

Example 7 with ObjectReferenceMapping

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

the class ObjectAccessor method initOneToOneMapping.

/**
 * INTERNAL:
 * Initialize a OneToOneMapping.
 */
protected ObjectReferenceMapping initOneToOneMapping() {
    // Allow for different descriptor types (EIS) to create different mapping types.
    ObjectReferenceMapping mapping = getDescriptor().getClassDescriptor().newOneToOneMapping();
    processRelationshipMapping(mapping);
    mapping.setIsOptional(isOptional());
    mapping.setDerivesId(derivesId());
    // Process the indirection.
    processIndirection(mapping);
    // Process a @ReturnInsert and @ReturnUpdate (to log a warning message)
    processReturnInsertAndUpdate();
    return mapping;
}
Also used : ObjectReferenceMapping(org.eclipse.persistence.mappings.ObjectReferenceMapping)

Example 8 with ObjectReferenceMapping

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

the class OneToOneAccessor method process.

/**
 * INTERNAL:
 * Process a one to one setting into an EclipseLink OneToOneMapping.
 */
@Override
public void process() {
    super.process();
    // Initialize our mapping now with what we found.
    ObjectReferenceMapping mapping = initOneToOneMapping();
    if (hasMappedBy()) {
        // Non-owning side, process the foreign keys from the owner.
        DatabaseMapping owningMapping = getOwningMapping();
        if (owningMapping.isOneToOneMapping()) {
            OneToOneMapping ownerMapping = (OneToOneMapping) owningMapping;
            // as we would for a many-to-many mapping.
            if (ownerMapping.hasRelationTableMechanism()) {
                // Put a relation table mechanism on our mapping.
                ((OneToOneMapping) mapping).setRelationTableMechanism(new RelationTableMechanism());
                processMappedByRelationTable(ownerMapping.getRelationTableMechanism(), ((OneToOneMapping) mapping).getRelationTableMechanism());
            } else {
                Map<DatabaseField, DatabaseField> targetToSourceKeyFields;
                Map<DatabaseField, DatabaseField> sourceToTargetKeyFields;
                // the primary key field to point to our own database table.
                if (getDescriptor().usesTablePerClassInheritanceStrategy()) {
                    targetToSourceKeyFields = new HashMap<DatabaseField, DatabaseField>();
                    sourceToTargetKeyFields = new HashMap<DatabaseField, DatabaseField>();
                    for (DatabaseField fkField : ownerMapping.getSourceToTargetKeyFields().keySet()) {
                        // We need to update the pk field to be to our table.
                        DatabaseField pkField = ownerMapping.getSourceToTargetKeyFields().get(fkField).clone();
                        pkField.setTable(getDescriptor().getPrimaryTable());
                        sourceToTargetKeyFields.put(fkField, pkField);
                        targetToSourceKeyFields.put(pkField, fkField);
                    }
                } else {
                    targetToSourceKeyFields = ownerMapping.getTargetToSourceKeyFields();
                    sourceToTargetKeyFields = ownerMapping.getSourceToTargetKeyFields();
                }
                ((OneToOneMapping) mapping).setSourceToTargetKeyFields(targetToSourceKeyFields);
                ((OneToOneMapping) mapping).setTargetToSourceKeyFields(sourceToTargetKeyFields);
            }
        } else {
            // If improper mapping encountered, throw an exception.
            throw ValidationException.invalidMapping(getJavaClass(), getReferenceClass());
        }
    } else if (mapping instanceof OneToOneMapping) {
        // Owning side, look for JoinColumns or PrimaryKeyJoinColumns.
        processOwningMappingKeys((OneToOneMapping) mapping);
    } else {
        processForeignKeyRelationship(mapping);
    }
}
Also used : ObjectReferenceMapping(org.eclipse.persistence.mappings.ObjectReferenceMapping) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping) RelationTableMechanism(org.eclipse.persistence.mappings.RelationTableMechanism)

Example 9 with ObjectReferenceMapping

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

the class CMP3Policy method initializePrimaryKeyFields.

/**
 * INTERNAL:
 * Cache the bean's primary key fields so speed up creating of primary key
 * objects and initialization of beans.
 *
 * Note, we have to re-look up the fields for the bean class since
 * these fields may have been loaded with the wrong loader (thank you Kirk).
 * If the key is compound, we also have to look up the fields for the key.
 */
protected KeyElementAccessor[] initializePrimaryKeyFields(Class<?> keyClass, AbstractSession session) {
    KeyElementAccessor[] pkAttributes = null;
    ClassDescriptor aDescriptor = this.getDescriptor();
    fieldToAccessorMap = new HashMap<DatabaseField, KeyElementAccessor>();
    int numberOfIDFields = aDescriptor.getPrimaryKeyFields().size();
    pkAttributes = new KeyElementAccessor[numberOfIDFields];
    Iterator<DatabaseField> attributesIter = aDescriptor.getPrimaryKeyFields().iterator();
    // Used fields in case it is an embedded class
    for (int i = 0; attributesIter.hasNext(); i++) {
        DatabaseField field = attributesIter.next();
        // We need to check all mappings for this field, not just the writable one and instead of
        // having multiple sections of duplicate code we'll just add the writable mapping directly
        // to the list.
        List allMappings = new ArrayList(1);
        addReadOnlyMappings(aDescriptor, field, allMappings);
        addWritableMapping(aDescriptor, field, allMappings);
        // This exception will be used to determine if the element (field or method) from
        // the mapping was found on the key class was found or not and throw an exception otherwise.
        Exception noSuchElementException = null;
        // Set the current key class ...
        Class<?> currentKeyClass = keyClass;
        // that mapping instead when we find it.
        for (int index = (allMappings.size() - 1); index >= 0; --index) {
            DatabaseMapping mapping = (DatabaseMapping) allMappings.get(index);
            // the id or not.
            if (aDescriptor.hasDerivedId() && !mapping.derivesId()) {
                // we initialize this portion of the composite id.
                if (mapping.isAggregateMapping() && allMappings.size() > 1) {
                    // Bail ... more mappings to check.
                    continue;
                }
            } else if (mapping.isForeignReferenceMapping() && !mapping.isOneToOneMapping()) {
                // JPA 2.0 allows DerrivedIds, so Id fields are either OneToOne or DirectToField mappings
                continue;
            }
            if (mapping.isAggregateMapping()) {
                // Either this aggregate is the key class, or we need to drill down further. Add the read
                // only and writable mappings from the aggregate.
                addReadOnlyMappings(mapping.getReferenceDescriptor(), field, allMappings);
                addWritableMapping(mapping.getReferenceDescriptor(), field, allMappings);
                // Since we added the mappings from this aggregate mapping, we should remove this aggregate
                // mapping from the allMappings list. Otherwise, if the mapping for the primary key field is
                // not found in the aggregate (or nested aggregate) then we will hit an infinite loop when
                // searching the aggregate and its mappings. Note: This is cautionary, since in reality, this
                // 'should' never happen, but if it does we certainly would rather throw an exception instead
                // of causing an infinite loop.
                allMappings.remove(mapping);
                // Update the index to parse the next mapping correctly.
                index = allMappings.size();
                // Update the key class now ...
                currentKeyClass = mapping.getReferenceDescriptor().getJavaClass();
            } else {
                String fieldName = (mapping.hasMapsIdValue()) ? mapping.getMapsIdValue() : mapping.getAttributeName();
                if (currentKeyClass == null || mapping.isMultitenantPrimaryKeyMapping()) {
                    // Without a currentKeyClass, the primary key is a non compound key but
                    // we may need to add any multitenant primary key mappings that are
                    // defined and we need an accessor for them. The same case will hold
                    // true when we do have a currentKeyClass. Multitenant primary keys
                    // must still be added.
                    pkAttributes[i] = new KeyIsElementAccessor(fieldName, field, mapping);
                    if (mapping.isAbstractDirectMapping()) {
                        setPKClass(ConversionManager.getObjectClass(mapping.getAttributeClassification()));
                    } else if (mapping.isOneToOneMapping()) {
                        ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                        // ensure the referenced descriptor was initialized
                        if (!session.isRemoteSession()) {
                            refDescriptor.initialize(session);
                        }
                        CMPPolicy refPolicy = refDescriptor.getCMPPolicy();
                        setPKClass(refPolicy.getPKClass());
                    }
                    fieldToAccessorMap.put(field, pkAttributes[i]);
                    noSuchElementException = null;
                } else {
                    if (mapping.isOneToOneMapping()) {
                        ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                        // ensure the referenced descriptor was initialized
                        if (!session.isRemoteSession()) {
                            refDescriptor.initialize(session);
                        }
                        CMPPolicy refPolicy = refDescriptor.getCMPPolicy();
                        if ((refPolicy != null) && refPolicy.isCMP3Policy() && (refPolicy.getPKClass() == currentKeyClass)) {
                            // Since the ref pk class is our pk class, get the accessor we need to pull the value out of the PK class for our field
                            OneToOneMapping refmapping = (OneToOneMapping) mapping;
                            DatabaseField targetKey = refmapping.getSourceToTargetKeyFields().get(field);
                            pkAttributes[i] = ((CMP3Policy) refPolicy).fieldToAccessorMap.get(targetKey);
                            // associate their accessor to our field so we can look it up when we need it
                            this.fieldToAccessorMap.put(field, pkAttributes[i]);
                            noSuchElementException = null;
                            break;
                        }
                    }
                    try {
                        pkAttributes[i] = new FieldAccessor(this, getField(currentKeyClass, fieldName), fieldName, field, mapping, currentKeyClass != keyClass);
                        fieldToAccessorMap.put(field, pkAttributes[i]);
                        noSuchElementException = null;
                    } catch (NoSuchFieldException ex) {
                        String getMethodName = null;
                        String setMethodName = null;
                        if (mapping.isObjectReferenceMapping() && ((ObjectReferenceMapping) mapping).getIndirectionPolicy().isWeavedObjectBasicIndirectionPolicy()) {
                            WeavedObjectBasicIndirectionPolicy weavedIndirectionPolicy = (WeavedObjectBasicIndirectionPolicy) ((ObjectReferenceMapping) mapping).getIndirectionPolicy();
                            if (weavedIndirectionPolicy.hasUsedMethodAccess()) {
                                getMethodName = weavedIndirectionPolicy.getGetMethodName();
                                setMethodName = weavedIndirectionPolicy.getSetMethodName();
                            }
                        } else {
                            getMethodName = mapping.getGetMethodName();
                            setMethodName = mapping.getSetMethodName();
                        }
                        if (getMethodName != null) {
                            // Must be a property.
                            try {
                                Method getMethod = null;
                                if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                    try {
                                        getMethod = AccessController.doPrivileged(new PrivilegedGetMethod(currentKeyClass, getMethodName, new Class<?>[] {}, true));
                                    } catch (PrivilegedActionException exception) {
                                        throw (NoSuchMethodException) exception.getException();
                                    }
                                } else {
                                    getMethod = PrivilegedAccessHelper.getMethod(currentKeyClass, getMethodName, new Class<?>[] {}, true);
                                }
                                Method setMethod = null;
                                if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
                                    try {
                                        setMethod = AccessController.doPrivileged(new PrivilegedGetMethod(currentKeyClass, setMethodName, new Class<?>[] { getMethod.getReturnType() }, true));
                                    } catch (PrivilegedActionException exception) {
                                        throw (NoSuchMethodException) exception.getException();
                                    }
                                } else {
                                    setMethod = PrivilegedAccessHelper.getMethod(currentKeyClass, setMethodName, new Class<?>[] { getMethod.getReturnType() }, true);
                                }
                                pkAttributes[i] = new PropertyAccessor(this, getMethod, setMethod, fieldName, field, mapping, currentKeyClass != keyClass);
                                this.fieldToAccessorMap.put(field, pkAttributes[i]);
                                noSuchElementException = null;
                            } catch (NoSuchMethodException exs) {
                                // not a field not a method, but a pk class is defined.  Check for other mappings
                                noSuchElementException = exs;
                            }
                        } else {
                            noSuchElementException = ex;
                        }
                        // accessor then we're dealing with a dynamic entity.
                        if (noSuchElementException != null && mapping.getAttributeAccessor().isValuesAccessor()) {
                            pkAttributes[i] = new ValuesFieldAccessor(fieldName, field, mapping, currentKeyClass != keyClass);
                            noSuchElementException = null;
                        }
                    }
                }
                if (mapping.derivesId() || noSuchElementException == null) {
                    // any more mappings
                    break;
                }
            }
        }
        if (noSuchElementException != null) {
            throw DescriptorException.errorUsingPrimaryKey(keyClass, getDescriptor(), noSuchElementException);
        }
    }
    return pkAttributes;
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) ArrayList(java.util.ArrayList) CMPPolicy(org.eclipse.persistence.descriptors.CMPPolicy) ArrayList(java.util.ArrayList) List(java.util.List) ObjectReferenceMapping(org.eclipse.persistence.mappings.ObjectReferenceMapping) PrivilegedActionException(java.security.PrivilegedActionException) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Method(java.lang.reflect.Method) PrivilegedGetMethod(org.eclipse.persistence.internal.security.PrivilegedGetMethod) DescriptorException(org.eclipse.persistence.exceptions.DescriptorException) PrivilegedActionException(java.security.PrivilegedActionException) WeavedObjectBasicIndirectionPolicy(org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy) PrivilegedGetMethod(org.eclipse.persistence.internal.security.PrivilegedGetMethod) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) OneToOneMapping(org.eclipse.persistence.mappings.OneToOneMapping)

Aggregations

ObjectReferenceMapping (org.eclipse.persistence.mappings.ObjectReferenceMapping)9 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)5 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)5 Expression (org.eclipse.persistence.expressions.Expression)2 ObjectExpression (org.eclipse.persistence.internal.expressions.ObjectExpression)2 QueryKeyExpression (org.eclipse.persistence.internal.expressions.QueryKeyExpression)2 InvalidObject (org.eclipse.persistence.internal.helper.InvalidObject)2 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)2 ResultSetRecord (org.eclipse.persistence.internal.sessions.ResultSetRecord)2 SimpleResultSetRecord (org.eclipse.persistence.internal.sessions.SimpleResultSetRecord)2 ForeignReferenceMapping (org.eclipse.persistence.mappings.ForeignReferenceMapping)2 OneToOneMapping (org.eclipse.persistence.mappings.OneToOneMapping)2 EntityManager (jakarta.persistence.EntityManager)1 Method (java.lang.reflect.Method)1 PrivilegedActionException (java.security.PrivilegedActionException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 CMPPolicy (org.eclipse.persistence.descriptors.CMPPolicy)1 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)1