Search in sources :

Example 26 with ApiAdapter

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

the class JoinMapStore method remove.

/**
 * Method to remove an entry from the map.
 * @param op ObjectProvider for the map.
 * @param key Key of the entry to remove.
 * @return The value that was removed.
 */
public V remove(ObjectProvider op, Object key) {
    if (!validateKeyForReading(op, key)) {
        return null;
    }
    V oldValue;
    boolean exists;
    try {
        oldValue = getValue(op, key);
        exists = true;
    } catch (NoSuchElementException e) {
        oldValue = null;
        exists = false;
    }
    ExecutionContext ec = op.getExecutionContext();
    if (exists) {
        removeInternal(op, key);
    }
    MapMetaData mapmd = ownerMemberMetaData.getMap();
    ApiAdapter api = ec.getApiAdapter();
    if (mapmd.isDependentKey() && !mapmd.isEmbeddedKey() && api.isPersistable(key)) {
        // Delete the key if it is dependent
        ec.deleteObjectInternal(key);
    }
    if (mapmd.isDependentValue() && !mapmd.isEmbeddedValue() && api.isPersistable(oldValue)) {
        if (!containsValue(op, oldValue)) {
            // Delete the value if it is dependent and is not keyed by another key
            ec.deleteObjectInternal(oldValue);
        }
    }
    return oldValue;
}
Also used : ExecutionContext(org.datanucleus.ExecutionContext) ApiAdapter(org.datanucleus.api.ApiAdapter) MapMetaData(org.datanucleus.metadata.MapMetaData) NoSuchElementException(java.util.NoSuchElementException)

Example 27 with ApiAdapter

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

the class EmbeddedMapping method setObject.

/**
 * Mutator for the embedded object in the datastore.
 * @param ec ExecutionContext
 * @param ps The Prepared Statement
 * @param param Param numbers in the PreparedStatement for the fields of this object
 * @param value The embedded object to use
 * @param ownerOP ObjectProvider of the owning object containing this embedded object
 * @param ownerFieldNumber Field number in the owning object where this is stored
 */
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] param, Object value, ObjectProvider ownerOP, int ownerFieldNumber) {
    if (value == null) {
        int n = 0;
        String nullColumn = null;
        String nullValue = null;
        if (emd != null) {
            nullColumn = emd.getNullIndicatorColumn();
            nullValue = emd.getNullIndicatorValue();
        }
        if (discrimMapping != null) {
            discrimMapping.setObject(ec, ps, new int[] { param[n] }, null);
            n++;
        }
        for (int i = 0; i < javaTypeMappings.size(); i++) {
            JavaTypeMapping mapping = javaTypeMappings.get(i);
            int[] posMapping = new int[mapping.getNumberOfDatastoreMappings()];
            for (int j = 0; j < posMapping.length; j++) {
                posMapping[j] = param[n++];
            }
            // in which case apply the required value
            if (nullColumn != null && nullValue != null && mapping.getMemberMetaData().getColumnMetaData().length > 0 && mapping.getMemberMetaData().getColumnMetaData()[0].getName().equals(nullColumn)) {
                // Try to cater for user having an integer based column and value
                if (mapping instanceof IntegerMapping || mapping instanceof BigIntegerMapping || mapping instanceof LongMapping || mapping instanceof ShortMapping) {
                    Object convertedValue = null;
                    try {
                        if (mapping instanceof IntegerMapping || mapping instanceof ShortMapping) {
                            convertedValue = Integer.valueOf(nullValue);
                        } else if (mapping instanceof LongMapping || mapping instanceof BigIntegerMapping) {
                            convertedValue = Long.valueOf(nullValue);
                        }
                    } catch (Exception e) {
                    }
                    mapping.setObject(ec, ps, posMapping, convertedValue);
                } else {
                    mapping.setObject(ec, ps, posMapping, nullValue);
                }
            } else {
                if (mapping.getNumberOfDatastoreMappings() > 0) {
                    mapping.setObject(ec, ps, posMapping, null);
                }
            }
        }
    } else {
        ApiAdapter api = ec.getApiAdapter();
        if (!api.isPersistable(value)) {
            throw new NucleusException(Localiser.msg("041016", value.getClass(), value)).setFatal();
        }
        AbstractClassMetaData embCmd = ec.getMetaDataManager().getMetaDataForClass(value.getClass(), ec.getClassLoaderResolver());
        ObjectProvider embOP = ec.findObjectProvider(value);
        if (embOP == null || api.getExecutionContext(value) == null) {
            // Assign a StateManager to manage our embedded object
            embOP = ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, value, false, ownerOP, ownerFieldNumber);
            embOP.setPcObjectType(objectType);
        }
        int n = 0;
        if (discrimMapping != null) {
            if (discrimMetaData.getStrategy() != DiscriminatorStrategy.NONE) {
                discrimMapping.setObject(ec, ps, new int[] { param[n] }, embCmd.getDiscriminatorValue());
            }
            n++;
        }
        for (int i = 0; i < javaTypeMappings.size(); i++) {
            JavaTypeMapping mapping = javaTypeMappings.get(i);
            int[] posMapping = new int[mapping.getNumberOfDatastoreMappings()];
            for (int j = 0; j < posMapping.length; j++) {
                posMapping[j] = param[n++];
            }
            // Retrieve value of member from Embedded StateManager
            int embAbsFieldNum = embCmd.getAbsolutePositionOfMember(mapping.getMemberMetaData().getName());
            if (embAbsFieldNum >= 0) {
                // Member is present in this embedded type
                Object fieldValue = embOP.provideField(embAbsFieldNum);
                if (mapping instanceof EmbeddedPCMapping) {
                    mapping.setObject(ec, ps, posMapping, fieldValue, embOP, embAbsFieldNum);
                } else {
                    if (mapping.getNumberOfDatastoreMappings() > 0) {
                        mapping.setObject(ec, ps, posMapping, fieldValue);
                    }
                }
            } else {
                mapping.setObject(ec, ps, posMapping, null);
            }
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ObjectProvider(org.datanucleus.state.ObjectProvider) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 28 with ApiAdapter

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

the class SerialisedReferenceMapping method getObject.

/**
 * Method to extract the value of the persistable from a ResultSet.
 * @param ec execution context
 * @param resultSet The ResultSet
 * @param exprIndex The parameter positions in the result set to use.
 * @param ownerOP ObjectProvider for the owning object
 * @param fieldNumber Absolute number of field in owner object
 * @return The (deserialised) persistable object
 */
public Object getObject(ExecutionContext ec, ResultSet resultSet, int[] exprIndex, ObjectProvider ownerOP, int fieldNumber) {
    Object obj = getDatastoreMapping(0).getObject(resultSet, exprIndex[0]);
    ApiAdapter api = ec.getApiAdapter();
    if (api.isPersistable(obj)) {
        // Assign a StateManager to the serialised object if none present
        ObjectProvider embSM = ec.findObjectProvider(obj);
        if (embSM == null || api.getExecutionContext(obj) == null) {
            ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, obj, false, ownerOP, fieldNumber);
        }
    }
    return obj;
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 29 with ApiAdapter

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

the class AbstractContainerMapping method setObject.

/**
 * Method to set a field in the passed JDBC PreparedStatement using this mapping.
 * Only valid when the collection is serialised.
 * @param ec ExecutionContext
 * @param ps The JDBC Prepared Statement to be populated
 * @param exprIndex The parameter positions in the JDBC statement to populate.
 * @param value The value to populate into it
 */
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] exprIndex, Object value) {
    if (mmd == null || !containerIsStoredInSingleColumn()) {
        throw new NucleusException(failureMessage("setObject")).setFatal();
    }
    ObjectProvider[] sms = null;
    ApiAdapter api = ec.getApiAdapter();
    if (value != null) {
        Collection smsColl = null;
        if (value instanceof java.util.Collection) {
            Iterator elementsIter = ((java.util.Collection) value).iterator();
            while (elementsIter.hasNext()) {
                Object elem = elementsIter.next();
                if (api.isPersistable(elem)) {
                    ObjectProvider sm = ec.findObjectProvider(elem);
                    if (sm != null) {
                        if (smsColl == null) {
                            smsColl = new HashSet();
                        }
                        smsColl.add(sm);
                    }
                }
            }
        } else if (value instanceof java.util.Map) {
            Iterator entriesIter = ((java.util.Map) value).entrySet().iterator();
            while (entriesIter.hasNext()) {
                Map.Entry entry = (Map.Entry) entriesIter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if (api.isPersistable(key)) {
                    ObjectProvider sm = ec.findObjectProvider(key);
                    if (sm != null) {
                        if (smsColl == null) {
                            smsColl = new HashSet();
                        }
                        smsColl.add(sm);
                    }
                }
                if (api.isPersistable(val)) {
                    ObjectProvider sm = ec.findObjectProvider(val);
                    if (sm != null) {
                        if (smsColl == null) {
                            smsColl = new HashSet();
                        }
                        smsColl.add(sm);
                    }
                }
            }
        }
        if (smsColl != null) {
            sms = (ObjectProvider[]) smsColl.toArray(new ObjectProvider[smsColl.size()]);
        }
    }
    if (sms != null) {
        // Set all PC objects as being stored (so we dont detach them in any serialisation process)
        for (int i = 0; i < sms.length; i++) {
            sms[i].setStoringPC();
        }
    }
    getDatastoreMapping(0).setObject(ps, exprIndex[0], value);
    if (sms != null) {
        // Unset all PC objects now they are stored
        for (int i = 0; i < sms.length; i++) {
            sms[i].unsetStoringPC();
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) Map(java.util.Map) Iterator(java.util.Iterator) Collection(java.util.Collection) ObjectProvider(org.datanucleus.state.ObjectProvider) NucleusException(org.datanucleus.exceptions.NucleusException) Map(java.util.Map) HashSet(java.util.HashSet)

Example 30 with ApiAdapter

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

the class MapMapping method postInsert.

/**
 * Method to be called after the insert of the owner class element.
 * @param ownerOP ObjectProvider of the owner
 */
public void postInsert(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    java.util.Map value = (java.util.Map) ownerOP.provideField(getAbsoluteFieldNumber());
    if (containerIsStoredInSingleColumn()) {
        // Do nothing when serialised since we are handled in the main request
        if (value != null) {
            if (mmd.getMap().keyIsPersistent() || mmd.getMap().valueIsPersistent()) {
                // Make sure all persistable keys/values have ObjectProviders
                Set entries = value.entrySet();
                Iterator iter = entries.iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    if (mmd.getMap().keyIsPersistent() && entry.getKey() != null) {
                        Object key = entry.getKey();
                        if (ec.findObjectProvider(key) == null || ec.getApiAdapter().getExecutionContext(key) == null) {
                            ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, key, false, ownerOP, mmd.getAbsoluteFieldNumber());
                        }
                    }
                    if (mmd.getMap().valueIsPersistent() && entry.getValue() != null) {
                        Object val = entry.getValue();
                        if (ec.findObjectProvider(val) == null || ec.getApiAdapter().getExecutionContext(val) == null) {
                            ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, val, false, ownerOP, mmd.getAbsoluteFieldNumber());
                        }
                    }
                }
            }
        }
        return;
    }
    if (value == null) {
        // replace null map with an empty SCO wrapper
        replaceFieldWithWrapper(ownerOP, null);
        return;
    }
    if (!mmd.isCascadePersist()) {
        // Check that all keys/values are persistent before continuing and throw exception if necessary
        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("007006", mmd.getFullFieldName()));
        }
        ApiAdapter api = ec.getApiAdapter();
        Set entries = value.entrySet();
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (api.isPersistable(entry.getKey())) {
                if (!api.isPersistent(entry.getKey()) && !api.isDetached(entry.getKey())) {
                    // Key is not persistent so throw exception
                    throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), entry.getKey());
                }
            }
            if (api.isPersistable(entry.getValue())) {
                if (!api.isPersistent(entry.getValue()) && !api.isDetached(entry.getValue())) {
                    // Value is not persistent so throw exception
                    throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), entry.getValue());
                }
            }
        }
    } else {
        // Reachability
        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("007007", mmd.getFullFieldName()));
        }
    }
    if (value.size() > 0) {
        // Add the entries direct to the datastore
        ((MapStore) table.getStoreManager().getBackingStoreForField(ownerOP.getExecutionContext().getClassLoaderResolver(), mmd, value.getClass())).putAll(ownerOP, value);
        // Create a SCO wrapper with the entries loaded
        replaceFieldWithWrapper(ownerOP, value);
    } else {
        if (mmd.getRelationType(ownerOP.getExecutionContext().getClassLoaderResolver()) == RelationType.MANY_TO_MANY_BI) {
            // Create a SCO wrapper, pass in null so it loads any from the datastore (on other side?)
            replaceFieldWithWrapper(ownerOP, null);
        } else {
            // Create a SCO wrapper, pass in empty map to avoid loading from DB (extra SQL)
            replaceFieldWithWrapper(ownerOP, value);
        }
    }
}
Also used : Set(java.util.Set) ApiAdapter(org.datanucleus.api.ApiAdapter) ReachableObjectNotCascadedException(org.datanucleus.exceptions.ReachableObjectNotCascadedException) ExecutionContext(org.datanucleus.ExecutionContext) Map(java.util.Map) Iterator(java.util.Iterator) MapStore(org.datanucleus.store.types.scostore.MapStore) Map(java.util.Map)

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