Search in sources :

Example 31 with ObjectProvider

use of org.datanucleus.state.ObjectProvider in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method findObject.

/**
 * Accessor for an object given the object id. If validate is false, we return the object
 * if found in the cache, or otherwise a Hollow object with that id. If validate is true
 * we check with the datastore and return an object with the FetchPlan fields loaded.
 * TODO Would be nice, when using checkInheritance, to be able to specify the "id" is an instance of class X or subclass. See IdentityUtils where we have the min class
 * @param id Id of the object.
 * @param validate Whether to validate the object state
 * @param checkInheritance Whether look to the database to determine which class this object is.
 * @param objectClassName Class name for the object with this id (if known, optional)
 * @return The Object with this id
 * @throws NucleusObjectNotFoundException if the object doesn't exist in the datastore
 */
public Object findObject(Object id, boolean validate, boolean checkInheritance, String objectClassName) {
    if (id == null) {
        throw new NucleusUserException(Localiser.msg("010044"));
    }
    IdentityStringTranslator translator = getNucleusContext().getIdentityManager().getIdentityStringTranslator();
    if (translator != null && id instanceof String) {
        // DataNucleus extension to translate input identities into valid persistent identities.
        id = translator.getIdentity(this, (String) id);
    }
    ApiAdapter api = getApiAdapter();
    boolean fromCache = false;
    // try to find object in cache(s)
    Object pc = getObjectFromCache(id);
    ObjectProvider op = null;
    if (pc != null) {
        // Found in L1/L2 cache
        fromCache = true;
        if (id instanceof SCOID) {
            if (api.isPersistent(pc) && !api.isNew(pc) && !api.isDeleted(pc) && !api.isTransactional(pc)) {
                // JDO [5.4.4] Cant return HOLLOW nondurable objects
                throw new NucleusUserException(Localiser.msg("010005"));
            }
        }
        if (api.isTransactional(pc)) {
            // JDO [12.6.5] If there's already an object with the same id and it's transactional, return it
            return pc;
        }
        op = findObjectProvider(pc);
    } else {
        // Find it direct from the store if the store supports that
        pc = getStoreManager().getPersistenceHandler().findObject(this, id);
        if (pc != null) {
            op = findObjectProvider(pc);
            putObjectIntoLevel1Cache(op);
            putObjectIntoLevel2Cache(op, false);
        } else {
            // Object not found yet, so maybe class name is not correct inheritance level
            ClassDetailsForId details = getClassDetailsForId(id, objectClassName, checkInheritance);
            String className = details.className;
            id = details.id;
            if (details.pc != null) {
                // Found during inheritance check via the cache
                pc = details.pc;
                op = findObjectProvider(pc);
                fromCache = true;
            } else {
                // Still not found, so create a Hollow instance with supplied PK values if possible
                try {
                    Class pcClass = clr.classForName(className, (id instanceof DatastoreId) ? null : id.getClass().getClassLoader());
                    if (Modifier.isAbstract(pcClass.getModifiers())) {
                        // This class is abstract so impossible to have an instance of this type
                        throw new NucleusObjectNotFoundException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id), className));
                    }
                    op = nucCtx.getObjectProviderFactory().newForHollow(this, pcClass, id);
                    pc = op.getObject();
                    if (!checkInheritance && !validate) {
                        // Mark the ObjectProvider as needing to validate this object before loading fields
                        op.markForInheritanceValidation();
                    }
                    // Cache the object in case we have bidirectional relations that would need to find this
                    putObjectIntoLevel1Cache(op);
                } catch (ClassNotResolvedException e) {
                    NucleusLogger.PERSISTENCE.warn(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)));
                    throw new NucleusUserException(Localiser.msg("010027", IdentityUtils.getPersistableIdentityForId(id)), e);
                }
            }
        }
    }
    boolean performValidationWhenCached = nucCtx.getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_FIND_OBJECT_VALIDATE_WHEN_CACHED);
    if (validate && (!fromCache || performValidationWhenCached)) {
        // loading any fetchplan fields that are needed in the process.
        if (!fromCache) {
            // Cache the object in case we have bidirectional relations that would need to find this
            putObjectIntoLevel1Cache(op);
        }
        try {
            op.validate();
            if (op.getObject() != pc) {
                // Underlying object was changed in the validation process. This can happen when the datastore
                // is responsible for managing object references and it no longer recognises the cached value.
                fromCache = false;
                pc = op.getObject();
                putObjectIntoLevel1Cache(op);
            }
        } catch (NucleusObjectNotFoundException onfe) {
            // Object doesn't exist, so remove from L1 cache
            removeObjectFromLevel1Cache(op.getInternalObjectId());
            throw onfe;
        }
    }
    if (!fromCache) {
        // Cache the object (update it if already present)
        putObjectIntoLevel2Cache(op, false);
    }
    return pc;
}
Also used : IdentityStringTranslator(org.datanucleus.identity.IdentityStringTranslator) ApiAdapter(org.datanucleus.api.ApiAdapter) DatastoreId(org.datanucleus.identity.DatastoreId) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) SCOID(org.datanucleus.identity.SCOID) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 32 with ObjectProvider

use of org.datanucleus.state.ObjectProvider in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method setObjectProviderAssociatedValue.

/* (non-Javadoc)
     * @see org.datanucleus.ExecutionContext#setObjectProviderAssociatedValue(org.datanucleus.state.ObjectProvider, java.lang.Object, java.lang.Object)
     */
public void setObjectProviderAssociatedValue(ObjectProvider op, Object key, Object value) {
    Map opMap = null;
    if (opAssociatedValuesMapByOP == null) {
        opAssociatedValuesMapByOP = new HashMap<ObjectProvider, Map<?, ?>>();
        opMap = new HashMap();
        opAssociatedValuesMapByOP.put(op, opMap);
    } else {
        opMap = opAssociatedValuesMapByOP.get(op);
        if (opMap == null) {
            opMap = new HashMap();
            opAssociatedValuesMapByOP.put(op, opMap);
        }
    }
    opMap.put(key, value);
}
Also used : ConcurrentReferenceHashMap(org.datanucleus.util.ConcurrentReferenceHashMap) HashMap(java.util.HashMap) ObjectProvider(org.datanucleus.state.ObjectProvider) ConcurrentReferenceHashMap(org.datanucleus.util.ConcurrentReferenceHashMap) Map(java.util.Map) HashMap(java.util.HashMap)

Example 33 with ObjectProvider

use of org.datanucleus.state.ObjectProvider in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method postCommit.

/**
 * Commit any changes made to objects managed by the object manager to the database.
 */
public void postCommit() {
    if (properties.getFrequentProperties().getDetachAllOnCommit()) {
        // Detach-all-on-commit
        performDetachAllOnTxnEnd();
    }
    List failures = null;
    try {
        // Commit all enlisted ObjectProviders
        ApiAdapter api = getApiAdapter();
        ObjectProvider[] ops = enlistedOPCache.values().toArray(new ObjectProvider[enlistedOPCache.size()]);
        for (int i = 0; i < ops.length; ++i) {
            try {
                // TODO this if is due to sms that can have lc == null, why?, should not be here then
                if (ops[i] != null && ops[i].getObject() != null && (api.isPersistent(ops[i].getObject()) || api.isTransactional(ops[i].getObject()))) {
                    ops[i].postCommit(getTransaction());
                    // TODO Change this check so that we remove all objects that are no longer suitable for caching
                    if (properties.getFrequentProperties().getDetachAllOnCommit() && api.isDetachable(ops[i].getObject())) {
                        // "DetachAllOnCommit" - Remove the object from the L1 cache since it is now detached
                        removeObjectProviderFromCache(ops[i]);
                    }
                }
            } catch (RuntimeException e) {
                if (failures == null) {
                    failures = new ArrayList();
                }
                failures.add(e);
            }
        }
    } finally {
        resetTransactionalVariables();
    }
    if (failures != null && !failures.isEmpty()) {
        throw new CommitStateTransitionException((Exception[]) failures.toArray(new Exception[failures.size()]));
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) CommitStateTransitionException(org.datanucleus.exceptions.CommitStateTransitionException) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ObjectProvider(org.datanucleus.state.ObjectProvider) ClassNotDetachableException(org.datanucleus.exceptions.ClassNotDetachableException) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) RollbackStateTransitionException(org.datanucleus.exceptions.RollbackStateTransitionException) NucleusException(org.datanucleus.exceptions.NucleusException) NucleusFatalUserException(org.datanucleus.exceptions.NucleusFatalUserException) ClassNotPersistableException(org.datanucleus.exceptions.ClassNotPersistableException) NoPersistenceInformationException(org.datanucleus.exceptions.NoPersistenceInformationException) TransactionActiveOnCloseException(org.datanucleus.exceptions.TransactionActiveOnCloseException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) NucleusOptimisticException(org.datanucleus.exceptions.NucleusOptimisticException) CommitStateTransitionException(org.datanucleus.exceptions.CommitStateTransitionException) TransactionNotActiveException(org.datanucleus.exceptions.TransactionNotActiveException) ObjectDetachedException(org.datanucleus.exceptions.ObjectDetachedException)

Example 34 with ObjectProvider

use of org.datanucleus.state.ObjectProvider in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method retrieveObject.

/**
 * Method to retrieve an object.
 * @param obj The object
 * @param fgOnly Whether to retrieve the current fetch group fields only
 */
public void retrieveObject(Object obj, boolean fgOnly) {
    if (obj == null) {
        return;
    }
    try {
        clr.setPrimary(obj.getClass().getClassLoader());
        assertClassPersistable(obj.getClass());
        assertNotDetached(obj);
        ObjectProvider op = findObjectProvider(obj);
        if (op == null) {
            throw new NucleusUserException(Localiser.msg("010048", StringUtils.toJVMIDString(obj), getApiAdapter().getIdForObject(obj), "retrieve"));
        }
        op.retrieve(fgOnly);
    } finally {
        clr.unsetPrimary();
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 35 with ObjectProvider

use of org.datanucleus.state.ObjectProvider in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method findObjectByUnique.

/* (non-Javadoc)
     * @see org.datanucleus.ExecutionContext#findObjectByUnique(java.lang.Class, java.lang.String[], java.lang.Object[])
     */
@Override
public <T> T findObjectByUnique(Class<T> cls, String[] memberNames, Object[] memberValues) {
    if (cls == null || memberNames == null || memberNames.length == 0 || memberValues == null || memberValues.length == 0) {
        throw new NucleusUserException(Localiser.msg("010053", cls, StringUtils.objectArrayToString(memberNames), StringUtils.objectArrayToString(memberValues)));
    }
    // Check class and member existence
    AbstractClassMetaData cmd = getMetaDataManager().getMetaDataForClass(cls, clr);
    if (cmd == null) {
        throw new NucleusUserException(Localiser.msg("010052", cls.getName()));
    }
    for (String memberName : memberNames) {
        AbstractMemberMetaData mmd = cmd.getMetaDataForMember(memberName);
        if (mmd == null) {
            throw new NucleusUserException("Attempt to find object using unique key of class " + cmd.getFullClassName() + " but field " + memberName + " doesnt exist!");
        }
    }
    // Check whether this is cached against the unique key
    CacheUniqueKey uniKey = new CacheUniqueKey(cls.getName(), memberNames, memberValues);
    ObjectProvider op = cache.getUnique(uniKey);
    if (op == null && l2CacheEnabled) {
        if (NucleusLogger.CACHE.isDebugEnabled()) {
            NucleusLogger.CACHE.debug(Localiser.msg("003007", uniKey));
        }
        // Try L2 cache
        Object pc = getObjectFromLevel2CacheForUnique(uniKey);
        if (pc != null) {
            op = findObjectProvider(pc);
        }
    }
    if (op != null) {
        return (T) op.getObject();
    }
    return (T) getStoreManager().getPersistenceHandler().findObjectForUnique(this, cmd, memberNames, memberValues);
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ObjectProvider(org.datanucleus.state.ObjectProvider) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) CacheUniqueKey(org.datanucleus.cache.CacheUniqueKey)

Aggregations

ObjectProvider (org.datanucleus.state.ObjectProvider)160 ExecutionContext (org.datanucleus.ExecutionContext)85 Iterator (java.util.Iterator)43 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)34 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)25 Map (java.util.Map)22 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)22 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)21 SQLException (java.sql.SQLException)17 Collection (java.util.Collection)16 ApiAdapter (org.datanucleus.api.ApiAdapter)16 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)16 SCOCollectionIterator (org.datanucleus.store.types.SCOCollectionIterator)16 ArrayList (java.util.ArrayList)14 HashSet (java.util.HashSet)14 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)14 NucleusException (org.datanucleus.exceptions.NucleusException)13 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)13 ListIterator (java.util.ListIterator)12 SQLController (org.datanucleus.store.rdbms.SQLController)12