Package org.datanucleus.store.connection

Examples of org.datanucleus.store.connection.ManagedConnection


  @Override
  public NucleusConnection getNucleusConnection(ExecutionContext ec) {
    ConnectionFactory cf = connectionMgr.lookupConnectionFactory(primaryConnectionFactoryName);

    final ManagedConnection mc;
    final boolean enlisted;
    enlisted = ec.getTransaction().isActive();
    mc = cf.getConnection(enlisted ? ec : null, ec.getTransaction(), null); // Will throw exception if already locked

    // Lock the connection now that it is in use by the user
    mc.lock();

    Runnable closeRunnable = new Runnable() {
      public void run() {
        // Unlock the connection now that the user has finished with it
        mc.unlock();
        if (!enlisted) {
          // TODO Anything to do here?
        }
      }
    };
    return new NucleusConnectionImpl(mc.getConnection(), closeRunnable);
  }
View Full Code Here


   * Each PM/EM has its own DatastoreService, and consequently can have a current DatastoreTransaction.
   * @param ec ExecutionContext
   * @return The DatastoreTransaction if active, or null
   */
  public DatastoreTransaction getDatastoreTransaction(ExecutionContext ec) {
    ManagedConnection mconn = ec.getStoreManager().getConnection(ec);
    return ((EmulatedXAResource) mconn.getXAResource()).getCurrentTransaction();
  }
View Full Code Here

   * Each PM/EM has its own DatastoreService.
   * @param ec ExecutionContext
   * @return The DatastoreService
   */
  public DatastoreService getDatastoreService(ExecutionContext ec) {
    ManagedConnection mconn = ec.getStoreManager().getConnection(ec);
    return ((EmulatedXAResource) mconn.getXAResource()).getDatastoreService();
  }
View Full Code Here

        for (String tableName : opsByTable.keySet())
        {
            Set<ObjectProvider> opsForTable = opsByTable.get(tableName);
            ExecutionContext ec = ops[0].getExecutionContext();
            ManagedConnection mconn = storeMgr.getConnection(ec);
            try
            {
                DB db = (DB)mconn.getConnection();
                long startTime = System.currentTimeMillis();

                DBCollection collection = db.getCollection(tableName);
                DBObject[] dbObjects = new DBObject[opsForTable.size()];
                int i=0;
                for (ObjectProvider op : opsForTable)
                {
                    storeMgr.assertReadOnlyForUpdateOfObject(op);
                    AbstractClassMetaData cmd = op.getClassMetaData();
                    if (!storeMgr.managesClass(cmd.getFullClassName()))
                    {
                        storeMgr.addClass(cmd.getFullClassName(), op.getExecutionContext().getClassLoaderResolver());
                    }

                    if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                    {
                        NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.Start",
                            op.toPrintableID(), op.getInternalObjectId()));
                    }

                    dbObjects[i] = getDBObjectForObjectProviderToInsert(op);

                    if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                    {
                        NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.ObjectPersisted",
                            op.toPrintableID(), op.getInternalObjectId()));
                    }

                    i++;
                }

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                {
                    NucleusLogger.DATASTORE_PERSIST.debug("Persisting objects as " + StringUtils.objectArrayToString(dbObjects));
                }
                collection.insert(dbObjects, new WriteConcern(1));

                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.ExecutionTime",
                        (System.currentTimeMillis() - startTime)));
                }
                if (storeMgr.getRuntimeManager() != null)
                {
                    for (int j=0;j<dbObjects.length;j++)
                    {
                        storeMgr.getRuntimeManager().incrementInsertCount();
                    }
                }
            }
            catch (MongoException me)
            {
                NucleusLogger.PERSISTENCE.error("Exception inserting objects", me);
                throw new NucleusDataStoreException("Exception inserting objects", me);
            }
            finally
            {
                mconn.release();
            }
        }
    }
View Full Code Here

        {
            storeMgr.addClass(cmd.getFullClassName(), op.getExecutionContext().getClassLoaderResolver());
        }

        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try
        {
            DB db = (DB)mconn.getConnection();

            long startTime = System.currentTimeMillis();
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.Start",
                    op.toPrintableID(), op.getInternalObjectId()));
            }

            DBCollection collection = db.getCollection(MongoDBUtils.getCollectionName(cmd));
            DBObject dbObject = getDBObjectForObjectProviderToInsert(op);

            NucleusLogger.DATASTORE_PERSIST.debug("Persisting object " + op + " as " + dbObject);
            collection.insert(dbObject, new WriteConcern(1));

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.ObjectPersisted",
                    op.toPrintableID(), op.getInternalObjectId()));
            }

            // Retrieve any datastore-generated IDENTITY strategy value as necessary
            if (cmd.getIdentityType() == IdentityType.DATASTORE &&
                cmd.getIdentityMetaData().getValueStrategy() == IdentityStrategy.IDENTITY)
            {
                // Set identity from MongoDB "_id" field
                ObjectId idKey = (ObjectId) dbObject.get("_id");
                op.setPostStoreNewObjectId(idKey.toString());
                if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                {
                    NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.ObjectPersistedWithIdentity",
                        op.toPrintableID(), idKey));
                }
            }
            else if (cmd.getIdentityType() == IdentityType.APPLICATION)
            {
                int[] pkFieldNumbers = cmd.getPKMemberPositions();
                for (int i=0;i<pkFieldNumbers.length;i++)
                {
                    AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]);
                    if (mmd.getValueStrategy() == IdentityStrategy.IDENTITY)
                    {
                        if (mmd.getType() != String.class)
                        {
                            // Field type must be String since MongoDB "_id" is a hex String.
                            throw new NucleusUserException("Any field using IDENTITY value generation with MongoDB should be of type String");
                        }
                        ObjectId idKey = (ObjectId)dbObject.get("_id");
                        op.replaceField(mmd.getAbsoluteFieldNumber(), idKey.toString());
                        op.setPostStoreNewObjectId(idKey); // TODO This is incorrect if part of a composite PK
                        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
                        {
                            NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Insert.ObjectPersistedWithIdentity",
                                op.toPrintableID(), idKey));
                        }
                    }
                }
            }

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.ExecutionTime",
                    (System.currentTimeMillis() - startTime)));
            }
            if (storeMgr.getRuntimeManager() != null)
            {
                storeMgr.getRuntimeManager().incrementInsertCount();
            }
        }
        catch (MongoException me)
        {
            NucleusLogger.PERSISTENCE.error("Exception inserting object " + op, me);
            throw new NucleusDataStoreException("Exception inserting object for " + op, me);
        }
        finally
        {
            mconn.release();
        }
    }
View Full Code Here

    public void updateObject(ObjectProvider op, int[] fieldNumbers)
    {
        storeMgr.assertReadOnlyForUpdateOfObject(op);

        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try
        {
            DB db = (DB)mconn.getConnection();

            long startTime = System.currentTimeMillis();
            AbstractClassMetaData cmd = op.getClassMetaData();
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                StringBuffer fieldStr = new StringBuffer();
                for (int i=0;i<fieldNumbers.length;i++)
                {
                    if (i > 0)
                    {
                        fieldStr.append(",");
                    }
                    fieldStr.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName());
                }
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Update.Start",
                    op.toPrintableID(), op.getInternalObjectId(), fieldStr.toString()));
            }

            DBCollection collection = db.getCollection(MongoDBUtils.getCollectionName(cmd));
            DBObject dbObject = MongoDBUtils.getObjectForObjectProvider(collection, op, true);
            if (dbObject == null)
            {
                if (cmd.hasVersionStrategy())
                {
                    throw new NucleusOptimisticException("Object with id " + op.getObjectId() +
                        " and version " + op.getTransactionalVersion() + " no longer present");
                }
                else
                {
                    throw new NucleusDataStoreException("Could not find object with id " + op.getObjectId());
                }
            }

            if (cmd.hasVersionStrategy())
            {
                // Version object so calculate version to store with
                Object currentVersion = op.getTransactionalVersion();
                VersionMetaData vermd = cmd.getVersionMetaData();
                Object nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), currentVersion);
                op.setTransactionalVersion(nextVersion);

                if (cmd.getVersionMetaData().getFieldName() != null)
                {
                    // Update the version field value
                    AbstractMemberMetaData verMmd = cmd.getMetaDataForMember(cmd.getVersionMetaData().getFieldName());
                    op.replaceField(verMmd.getAbsoluteFieldNumber(), nextVersion);
                }
                else
                {
                    // Update the stored surrogate value
                    String fieldName = MongoDBUtils.getFieldName(cmd.getVersionMetaData());
                    dbObject.put(fieldName, nextVersion);
                }
            }

            StoreFieldManager fieldManager = new StoreFieldManager(op, dbObject, cmd);
            op.provideFields(cmd.getAllMemberPositions(), fieldManager);
            collection.save(dbObject);

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.ExecutionTime",
                    (System.currentTimeMillis() - startTime)));
            }
            if (storeMgr.getRuntimeManager() != null)
            {
                storeMgr.getRuntimeManager().incrementUpdateCount();
            }
        }
        catch (MongoException me)
        {
            NucleusLogger.PERSISTENCE.error("Exception updating object " + op, me);
            throw new NucleusDataStoreException("Exception updating object for " + op, me);
        }
        finally
        {
            mconn.release();
        }
    }
View Full Code Here

        storeMgr.assertReadOnlyForUpdateOfObject(op);

        AbstractClassMetaData cmd = op.getClassMetaData();

        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try
        {
            DB db = (DB)mconn.getConnection();
            long startTime = System.currentTimeMillis();
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.Delete.Start",
                    op.toPrintableID(), op.getInternalObjectId()));
            }

            DBCollection collection = db.getCollection(MongoDBUtils.getCollectionName(cmd));
            DBObject dbObject = MongoDBUtils.getObjectForObjectProvider(collection, op, true);
            if (dbObject == null)
            {
                if (cmd.hasVersionStrategy())
                {
                    throw new NucleusOptimisticException("Object with id " + op.getObjectId() +
                        " and version " + op.getTransactionalVersion() + " no longer present");
                }
                else
                {
                    throw new NucleusDataStoreException("Could not find object with id " + op.getObjectId());
                }
            }

            // Invoke any cascade deletion
            op.loadUnloadedFields();
            op.provideFields(cmd.getAllMemberPositions(), new DeleteFieldManager(op));

            // Delete this object
            collection.remove(dbObject);

            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_PERSIST.debug(LOCALISER.msg("MongoDB.ExecutionTime",
                    (System.currentTimeMillis() - startTime)));
            }
            if (storeMgr.getRuntimeManager() != null)
            {
                storeMgr.getRuntimeManager().incrementDeleteCount();
            }
        }
        catch (MongoException me)
        {
            NucleusLogger.PERSISTENCE.error("Exception deleting object " + op, me);
            throw new NucleusDataStoreException("Exception deleting object for " + op, me);
        }
        finally
        {
            mconn.release();
        }
    }
View Full Code Here

    public void fetchObject(ObjectProvider op, int[] fieldNumbers)
    {
        AbstractClassMetaData cmd = op.getClassMetaData();

        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnection(ec);
        try
        {
            DB db = (DB)mconn.getConnection();
            if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled())
            {
                // Debug information about what we are retrieving
                StringBuffer str = new StringBuffer("Fetching object \"");
                str.append(op.toPrintableID()).append("\" (id=");
                str.append(op.getExecutionContext().getApiAdapter().getObjectId(op)).append(")").append(" fields [");
                for (int i=0;i<fieldNumbers.length;i++)
                {
                    if (i > 0)
                    {
                        str.append(",");
                    }
                    str.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]).getName());
                }
                str.append("]");
                NucleusLogger.DATASTORE_RETRIEVE.debug(str);
            }

            long startTime = System.currentTimeMillis();
            if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_RETRIEVE.debug(LOCALISER.msg("MongoDB.Fetch.Start",
                    op.toPrintableID(), op.getInternalObjectId()));
            }

            DBCollection collection = db.getCollection(MongoDBUtils.getCollectionName(cmd));
            DBObject dbObject = MongoDBUtils.getObjectForObjectProvider(collection, op, false);
            if (dbObject == null)
            {
                throw new NucleusObjectNotFoundException("Could not find object with id " + op.getInternalObjectId() + " op="+op);
            }

            if (cmd.hasVersionStrategy() && op.getTransactionalVersion() == null)
            {
                // No version set, so retrieve it
                if (cmd.getVersionMetaData().getFieldName() != null)
                {
                    // Version stored in a field
                    Object datastoreVersion =
                        op.provideField(cmd.getAbsolutePositionOfMember(cmd.getVersionMetaData().getFieldName()));
                    op.setVersion(datastoreVersion);
                }
                else
                {
                    // Surrogate version
                    String fieldName = MongoDBUtils.getFieldName(cmd.getVersionMetaData());
                    Object datastoreVersion = dbObject.get(fieldName);
                    op.setVersion(datastoreVersion);
                }
            }

            FetchFieldManager fieldManager = new FetchFieldManager(op, dbObject, cmd);
            op.replaceFields(fieldNumbers, fieldManager);

            if (NucleusLogger.DATASTORE_RETRIEVE.isDebugEnabled())
            {
                NucleusLogger.DATASTORE_RETRIEVE.debug(LOCALISER.msg("MongoDB.ExecutionTime",
                    (System.currentTimeMillis() - startTime)));
            }
            if (storeMgr.getRuntimeManager() != null)
            {
                storeMgr.getRuntimeManager().incrementFetchCount();
            }
        }
        finally
        {
            mconn.release();
        }
    }
View Full Code Here

        final AbstractClassMetaData cmd = op.getClassMetaData();
        if (cmd.getIdentityType() == IdentityType.APPLICATION ||
            cmd.getIdentityType() == IdentityType.DATASTORE)
        {
            ExecutionContext ec = op.getExecutionContext();
            ManagedConnection mconn = storeMgr.getConnection(ec);
            try
            {
                DB db = (DB)mconn.getConnection();
                DBCollection collection = db.getCollection(MongoDBUtils.getCollectionName(cmd));
                DBObject dbObject = MongoDBUtils.getObjectForObjectProvider(collection, op, false);
                if (dbObject == null)
                {
                    throw new NucleusObjectNotFoundException();
                }
            }
            finally
            {
                mconn.release();
            }
        }
    }
View Full Code Here

        }
    }
   
    protected Object performExecute(Map parameters)
    {
        ManagedConnection mconn = ec.getStoreManager().getConnection(ec);
        try
        {
            DB db = (DB)mconn.getConnection();

            long startTime = System.currentTimeMillis();
            if (NucleusLogger.QUERY.isDebugEnabled())
            {
                NucleusLogger.QUERY.debug(LOCALISER.msg("021046", "JPQL", getSingleStringQuery(), null));
            }
            List candidates = null;
            if (candidateCollection != null)
            {
                candidates = new ArrayList(candidateCollection);
            }
            else
            {
                BasicDBObject filterObject = null;
                if (datastoreCompilation != null)
                {
                    if (datastoreCompilation.isFilterComplete())
                    {
                        filterObject = datastoreCompilation.getFilter();
                    }
                }

                Map<String, Object> options = new HashMap();
                if (getBooleanExtensionProperty("slave-ok", false))
                {
                    options.put("slave-ok", true);
                }

                // Execute as much as possible in the datastore
                candidates = MongoDBUtils.getObjectsOfCandidateType(ec, db, candidateClass, subclasses,
                    ignoreCache, getFetchPlan(), filterObject, options);
            }

            // Apply any result restrictions to the results
            JavaQueryEvaluator resultMapper = new JPQLEvaluator(this, candidates, compilation,
                parameters, ec.getClassLoaderResolver());
            Collection results = resultMapper.execute(true, true, true, true, true);

            if (NucleusLogger.QUERY.isDebugEnabled())
            {
                NucleusLogger.QUERY.debug(LOCALISER.msg("021074", "JPQL",
                    "" + (System.currentTimeMillis() - startTime)));
            }

            if (type == BULK_DELETE)
            {
                ec.deleteObjects(results.toArray());
                return Long.valueOf(results.size());
            }
            else if (type == BULK_UPDATE)
            {
                throw new NucleusException("Bulk Update is not yet supported");
            }
            else
            {
                return results;
            }
        }
        finally
        {
            mconn.release();
        }
    }
View Full Code Here

TOP

Related Classes of org.datanucleus.store.connection.ManagedConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.