Search in sources :

Example 51 with ApiAdapter

use of org.datanucleus.api.ApiAdapter in project datanucleus-core by datanucleus.

the class SCOUtils method attachForCollection.

/**
 * Convenience method to attach (recursively) all elements for a collection field. All elements that are
 * persistable and not yet having an attached object will be attached.
 * @param ownerOP ObjectProvider for the owning object with the collection
 * @param elements The elements to process
 * @param elementsWithoutIdentity Whether the elements have their own identity
 */
public static void attachForCollection(ObjectProvider ownerOP, Object[] elements, boolean elementsWithoutIdentity) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    ApiAdapter api = ec.getApiAdapter();
    for (int i = 0; i < elements.length; i++) {
        if (api.isPersistable(elements[i])) {
            Object attached = ec.getAttachedObjectForId(api.getIdForObject(elements[i]));
            if (attached == null) {
                // Not yet attached so attach
                ec.attachObject(ownerOP, elements[i], elementsWithoutIdentity);
            }
        }
    }
}
Also used : ExecutionContext(org.datanucleus.ExecutionContext) ApiAdapter(org.datanucleus.api.ApiAdapter)

Example 52 with ApiAdapter

use of org.datanucleus.api.ApiAdapter in project datanucleus-core by datanucleus.

the class SCOUtils method attachCopyElements.

/**
 * Convenience method for use by Collection/Set/HashSet attachCopy methods to add any new elements (added
 * whilst detached) to the collection.
 * @param ownerOP Owner ObjectProvider
 * @param scoColl The current (attached) SCO collection
 * @param detachedElements The collection of (detached) elements that we're merging
 * @param elementsWithoutId Whether the elements have no identity
 * @return If the Collection was updated
 */
public static boolean attachCopyElements(ObjectProvider ownerOP, Collection scoColl, Collection detachedElements, boolean elementsWithoutId) {
    boolean updated = false;
    ApiAdapter api = ownerOP.getExecutionContext().getApiAdapter();
    // Delete any elements that are no longer in the collection
    Iterator scoCollIter = scoColl.iterator();
    while (scoCollIter.hasNext()) {
        Object currentElem = scoCollIter.next();
        Object currentElemId = api.getIdForObject(currentElem);
        Iterator desiredIter = detachedElements.iterator();
        boolean contained = false;
        if (elementsWithoutId) {
            contained = detachedElements.contains(currentElem);
        } else {
            while (desiredIter.hasNext()) {
                Object desiredElem = desiredIter.next();
                if (currentElemId != null) {
                    if (currentElemId.equals(api.getIdForObject(desiredElem))) {
                        // Identity equal so same
                        contained = true;
                        break;
                    }
                } else {
                    if (currentElem == desiredElem) {
                        // Same object
                        contained = true;
                        break;
                    }
                }
            }
        }
        if (!contained) {
            // No longer present so remove it
            scoCollIter.remove();
            updated = true;
        }
    }
    Iterator detachedElementsIter = detachedElements.iterator();
    while (detachedElementsIter.hasNext()) {
        Object detachedElement = detachedElementsIter.next();
        if (elementsWithoutId) {
            // Non-PC element
            if (!scoColl.contains(detachedElement)) {
                scoColl.add(detachedElement);
                updated = true;
            }
        } else {
            // PC element, so compare by id (if present)
            Object detachedElemId = api.getIdForObject(detachedElement);
            scoCollIter = scoColl.iterator();
            boolean contained = false;
            while (scoCollIter.hasNext()) {
                Object scoCollElem = scoCollIter.next();
                Object scoCollElemId = api.getIdForObject(scoCollElem);
                if (scoCollElemId != null && scoCollElemId.equals(detachedElemId)) {
                    contained = true;
                    break;
                }
            }
            if (!contained) {
                scoColl.add(detachedElement);
                updated = true;
            } else {
                ownerOP.getExecutionContext().attachObjectCopy(ownerOP, detachedElement, false);
            }
        }
    }
    return updated;
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) Iterator(java.util.Iterator)

Example 53 with ApiAdapter

use of org.datanucleus.api.ApiAdapter in project datanucleus-core by datanucleus.

the class AttachFieldManager method storeObjectField.

/**
 * Method to store an object field into the attached instance.
 * @param fieldNumber Number of the field to store
 * @param value the value in the detached instance
 */
public void storeObjectField(int fieldNumber, Object value) {
    // Note : when doing updates always do replaceField first and makeDirty after since the replaceField
    // can cause flush() to be called meaning that an update with null would be made before the new value
    // makes it into the field
    AbstractClassMetaData cmd = attachedOP.getClassMetaData();
    AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);
    ExecutionContext ec = attachedOP.getExecutionContext();
    RelationType relationType = mmd.getRelationType(ec.getClassLoaderResolver());
    // boolean processWhenExisting = true;
    if (mmd.hasExtension("attach")) {
        if (mmd.getValueForExtension("attach").equalsIgnoreCase("never")) {
            // Member is tagged to not attach, so put a null
            attachedOP.replaceFieldMakeDirty(fieldNumber, null);
            return;
        }
    // TODO Support attach only when not present in the datastore (only for PCs)
    // else if (mmd.getValueForExtension("attach").equalsIgnoreCase("when-non-existing"))
    // {
    // processWhenExisting = false;
    // }
    }
    // Use ContainerHandlers to support non-JDK Collections and single element collections
    ApiAdapter api = ec.getApiAdapter();
    if (value == null) {
        Object oldValue = null;
        if (mmd.isDependent() && persistent) {
            // Get any old value of this field so we can do cascade-delete if being nulled
            try {
                attachedOP.loadFieldFromDatastore(fieldNumber);
            } catch (Exception e) {
            // Error loading the field so didn't exist before attaching anyway
            }
            oldValue = attachedOP.provideField(fieldNumber);
        }
        attachedOP.replaceField(fieldNumber, null);
        if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
        if (mmd.isDependent() && !mmd.isEmbedded() && oldValue != null && api.isPersistable(oldValue)) {
            // Check for a field storing a PC where it is being nulled and the other object is dependent
            // Flush the nulling of the field
            attachedOP.flush();
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("026026", oldValue, mmd.getFullFieldName()));
            ec.deleteObjectInternal(oldValue);
        }
    } else if (secondClassMutableFields[fieldNumber]) {
        if (mmd.isSerialized() && !RelationType.isRelationMultiValued(relationType)) {
            // SCO Field is serialised, and no persistable elements so just update the column with this new value
            attachedOP.replaceFieldMakeDirty(fieldNumber, value);
            attachedOP.makeDirty(fieldNumber);
        } else {
            // Make sure that the value is a SCO wrapper
            Object oldValue = null;
            if (persistent && !attachedOP.isFieldLoaded(fieldNumber)) {
                attachedOP.loadField(fieldNumber);
            }
            oldValue = attachedOP.provideField(fieldNumber);
            boolean changed = dirtyFields[fieldNumber];
            if (!changed) {
                // Check if the new value is different (not detected if detached field was not a wrapper and mutable)
                if (oldValue == null) {
                    changed = true;
                } else {
                    if (mmd.hasCollection() && relationType != RelationType.NONE) {
                        boolean collsEqual = SCOUtils.collectionsAreEqual(api, (Collection) oldValue, (Collection) value);
                        changed = !collsEqual;
                    } else // TODO Do like the above for relational Maps
                    {
                        changed = !(oldValue.equals(value));
                    }
                }
            }
            SCO sco;
            if (oldValue == null || !(oldValue instanceof SCO)) {
                // Detached object didn't use wrapped field
                if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                    NucleusLogger.PERSISTENCE.debug(Localiser.msg("026029", StringUtils.toJVMIDString(attachedOP.getObject()), attachedOP.getInternalObjectId(), mmd.getName()));
                }
                sco = ec.getTypeManager().createSCOInstance(attachedOP, mmd, value != null ? value.getClass() : null, null, false);
                if (sco instanceof SCOContainer) {
                    // Load any containers to avoid update issues
                    ((SCOContainer) sco).load();
                }
                attachedOP.replaceFieldMakeDirty(fieldNumber, sco);
            } else {
                // The field is already a SCO wrapper, so just copy the new values to it
                sco = (SCO) oldValue;
            }
            if (cascadeAttach) {
                // Only trigger the cascade when required
                if (copy) {
                    // Attach copy of the SCO
                    sco.attachCopy(value);
                } else {
                    // Should be changed to do things like in attachCopy above.
                    if (sco instanceof Collection) {
                        // Attach all PC elements of the collection
                        SCOUtils.attachForCollection(attachedOP, ((Collection) value).toArray(), SCOUtils.collectionHasElementsWithoutIdentity(mmd));
                    } else if (sco instanceof Map) {
                        // Attach all PC keys/values of the map
                        SCOUtils.attachForMap(attachedOP, ((Map) value).entrySet(), SCOUtils.mapHasKeysWithoutIdentity(mmd), SCOUtils.mapHasValuesWithoutIdentity(mmd));
                    } else {
                        // Initialise the SCO with the new value
                        sco.initialise(value);
                    }
                }
            }
            if (changed || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        }
    } else if (mmd.getType().isArray() && RelationType.isRelationMultiValued(relationType)) {
        // Array of persistable objects
        if (mmd.isSerialized() || mmd.isEmbedded()) {
            // Field is serialised/embedded so just update the column with this new value TODO Make sure they have ObjectProviders
            attachedOP.replaceField(fieldNumber, value);
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        } else {
            Object oldValue = attachedOP.provideField(fieldNumber);
            if (oldValue == null && !attachedOP.getLoadedFields()[fieldNumber] && persistent) {
                // Retrieve old value for field
                attachedOP.loadField(fieldNumber);
                oldValue = attachedOP.provideField(fieldNumber);
            }
            if (cascadeAttach) {
                // Only trigger the cascade when required
                Object arr = Array.newInstance(mmd.getType().getComponentType(), Array.getLength(value));
                for (int i = 0; i < Array.getLength(value); i++) {
                    Object elem = Array.get(value, i);
                    // TODO Compare with old value and handle delete dependent etc
                    if (copy) {
                        Object elemAttached = ec.attachObjectCopy(attachedOP, elem, false);
                        Array.set(arr, i, elemAttached);
                    } else {
                        ec.attachObject(attachedOP, elem, false);
                        Array.set(arr, i, elem);
                    }
                }
                attachedOP.replaceFieldMakeDirty(fieldNumber, arr);
            }
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        }
    } else if (RelationType.isRelationSingleValued(relationType)) {
        // 1-1/N-1
        ObjectProvider valueSM = ec.findObjectProvider(value);
        if (valueSM != null && valueSM.getReferencedPC() != null && !api.isPersistent(value)) {
            // Value has ObjectProvider and has referenced object so is being attached, so refer to attached PC
            if (dirtyFields[fieldNumber]) {
                attachedOP.replaceFieldMakeDirty(fieldNumber, valueSM.getReferencedPC());
            } else {
                attachedOP.replaceField(fieldNumber, valueSM.getReferencedPC());
            }
        }
        if (cascadeAttach) {
            // Determine if field is persisted into the owning object (embedded/serialised)
            boolean sco = mmd.getEmbeddedMetaData() != null || mmd.isSerialized() || mmd.isEmbedded();
            if (copy) {
                // Attach copy of the PC
                value = ec.attachObjectCopy(attachedOP, value, sco);
                if (sco || dirtyFields[fieldNumber]) {
                    // Either embedded/serialised or marked as changed, so make it dirty
                    attachedOP.replaceFieldMakeDirty(fieldNumber, value);
                } else {
                    attachedOP.replaceField(fieldNumber, value);
                }
            } else {
                // Attach PC in-situ
                ec.attachObject(attachedOP, value, sco);
            }
            // Make sure the field is marked as dirty
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            } else if (sco && value != null && api.isDirty(value)) {
                attachedOP.makeDirty(fieldNumber);
            }
        } else if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
    } else {
        attachedOP.replaceField(fieldNumber, value);
        if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SCOContainer(org.datanucleus.store.types.SCOContainer) ExecutionContext(org.datanucleus.ExecutionContext) RelationType(org.datanucleus.metadata.RelationType) Collection(java.util.Collection) ObjectProvider(org.datanucleus.state.ObjectProvider) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) SCO(org.datanucleus.store.types.SCO)

Aggregations

ApiAdapter (org.datanucleus.api.ApiAdapter)53 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)19 ObjectProvider (org.datanucleus.state.ObjectProvider)16 ExecutionContext (org.datanucleus.ExecutionContext)12 Map (java.util.Map)11 NucleusException (org.datanucleus.exceptions.NucleusException)11 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)10 Iterator (java.util.Iterator)8 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)8 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)8 Collection (java.util.Collection)7 HashMap (java.util.HashMap)7 RelationType (org.datanucleus.metadata.RelationType)7 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)7 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)6 ClassNotResolvedException (org.datanucleus.exceptions.ClassNotResolvedException)6 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)5 SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)5 TypeManager (org.datanucleus.store.types.TypeManager)5 SortedMap (java.util.SortedMap)4