{
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();
}
}