Example usage for org.springframework.data.mongodb.core MongoTemplate execute

List of usage examples for org.springframework.data.mongodb.core MongoTemplate execute

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core MongoTemplate execute.

Prototype

public <T> T execute(DbCallback<T> action) 

Source Link

Usage

From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java

/**
 * Indexes any properties that are mapped with index:true
 * @param entity The entity//from   w w w. j  a  v a2 s.co m
 * @param template The template
 */
protected void initializeIndices(final PersistentEntity entity, final MongoTemplate template) {
    template.execute(new DbCallback<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public Object doInDB(DB db) throws MongoException, DataAccessException {
            final DBCollection collection = db.getCollection(getCollectionName(entity));

            final ClassMapping<MongoCollection> classMapping = entity.getMapping();
            if (classMapping != null) {
                final MongoCollection mappedForm = classMapping.getMappedForm();
                if (mappedForm != null) {
                    for (Map compoundIndex : mappedForm.getCompoundIndices()) {
                        DBObject indexDef = new BasicDBObject(compoundIndex);
                        collection.ensureIndex(indexDef);
                    }
                }
            }

            for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) {
                final boolean indexed = isIndexed(property);

                if (indexed) {
                    final MongoAttribute mongoAttributeMapping = property.getMapping().getMappedForm();
                    DBObject dbObject = new BasicDBObject();
                    final String fieldName = getMongoFieldNameForProperty(property);
                    dbObject.put(fieldName, 1);
                    DBObject options = new BasicDBObject();
                    if (mongoAttributeMapping != null) {
                        Map attributes = mongoAttributeMapping.getIndexAttributes();
                        if (attributes != null) {
                            attributes = new HashMap(attributes);
                            if (attributes.containsKey(MongoAttribute.INDEX_TYPE)) {
                                dbObject.put(fieldName, attributes.remove(MongoAttribute.INDEX_TYPE));
                            }
                            options.putAll(attributes);
                        }
                    }
                    if (options.toMap().isEmpty()) {
                        collection.ensureIndex(dbObject);
                    } else {
                        collection.ensureIndex(dbObject, options);
                    }
                }
            }

            return null;
        }

        String getMongoFieldNameForProperty(PersistentProperty<MongoAttribute> property) {
            PropertyMapping<MongoAttribute> pm = property.getMapping();
            String propKey = null;
            if (pm.getMappedForm() != null) {
                propKey = pm.getMappedForm().getField();
            }
            if (propKey == null) {
                propKey = property.getName();
            }
            return propKey;
        }
    });
}

From source file:org.grails.datastore.mapping.mongo.MongoSession.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void flushPendingInserts(final Map<PersistentEntity, Collection<PendingInsert>> inserts) {
    // Optimizes saving multipe entities at once
    for (final PersistentEntity entity : inserts.keySet()) {
        final MongoTemplate template = getMongoTemplate(entity.isRoot() ? entity : entity.getRootEntity());
        final String collectionNameToUse = getCollectionName(entity.isRoot() ? entity : entity.getRootEntity());
        template.execute(new DbCallback<Object>() {
            public Object doInDB(DB db) throws MongoException, DataAccessException {
                WriteConcern writeConcernToUse = writeConcern;

                writeConcernToUse = getDeclaredWriteConcern(writeConcernToUse, entity);
                final DBCollection collection = db.getCollection(collectionNameToUse);

                final Collection<PendingInsert> pendingInserts = inserts.get(entity);
                List<DBObject> dbObjects = new LinkedList<DBObject>();
                List<PendingOperation> postOperations = new LinkedList<PendingOperation>();

                for (PendingInsert pendingInsert : pendingInserts) {

                    final List<PendingOperation> preOperations = pendingInsert.getPreOperations();
                    for (PendingOperation preOperation : preOperations) {
                        preOperation.run();
                    }//from  w  w w .j av a2 s . com

                    dbObjects.add((DBObject) pendingInsert.getNativeEntry());
                    postOperations.addAll(pendingInsert.getCascadeOperations());
                    pendingInsert.run();
                }

                WriteResult writeResult = collection.insert(dbObjects.toArray(new DBObject[dbObjects.size()]),
                        writeConcernToUse);
                if (writeResult.getError() != null) {
                    errorOccured = true;
                    throw new DataIntegrityViolationException(writeResult.getError());
                }
                for (PendingOperation pendingOperation : postOperations) {
                    pendingOperation.run();
                }
                return null;
            }
        });
    }
}

From source file:org.grails.datastore.mapping.mongo.query.MongoQuery.java

@SuppressWarnings("hiding")
@Override/*from  w w  w. j  a va 2 s.  co m*/
protected List executeQuery(final PersistentEntity entity, final Junction criteria) {
    final MongoTemplate template = mongoSession.getMongoTemplate(entity);

    return template.execute(new DbCallback<List>() {
        @SuppressWarnings("unchecked")
        public List doInDB(DB db) throws MongoException, DataAccessException {

            final DBCollection collection = db.getCollection(mongoEntityPersister.getCollectionName(entity));
            if (uniqueResult) {
                final DBObject dbObject;
                if (criteria.isEmpty()) {
                    if (entity.isRoot()) {
                        dbObject = collection.findOne();
                    } else {
                        dbObject = collection.findOne(new BasicDBObject(MongoEntityPersister.MONGO_CLASS_FIELD,
                                entity.getDiscriminator()));
                    }
                } else {
                    dbObject = collection.findOne(getMongoQuery());
                }
                return wrapObjectResultInList(createObjectFromDBObject(dbObject));
            }

            DBCursor cursor = null;
            DBObject query = createQueryObject(entity);

            final List<Projection> projectionList = projections().getProjectionList();
            if (projectionList.isEmpty()) {
                cursor = executeQuery(entity, criteria, collection, query);
                return (List) new MongoResultList(cursor, mongoEntityPersister).clone();
            }

            List projectedResults = new ArrayList();
            for (Projection projection : projectionList) {
                if (projection instanceof CountProjection) {
                    // For some reason the below doesn't return the expected result whilst executing the query and returning the cursor does
                    //projectedResults.add(collection.getCount(query));
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    projectedResults.add(cursor.size());
                } else if (projection instanceof MinProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MinProjection mp = (MinProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.min((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof MaxProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    MaxProjection mp = (MaxProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.max((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));
                } else if (projection instanceof CountDistinctProjection) {
                    if (cursor == null)
                        cursor = executeQuery(entity, criteria, collection, query);
                    CountDistinctProjection mp = (CountDistinctProjection) projection;

                    MongoResultList results = new MongoResultList(cursor, mongoEntityPersister);
                    projectedResults.add(manualProjections.countDistinct((Collection) results.clone(),
                            getPropertyName(entity, mp.getPropertyName())));

                } else if ((projection instanceof PropertyProjection) || (projection instanceof IdProjection)) {
                    final PersistentProperty persistentProperty;
                    final String propertyName;
                    if (projection instanceof IdProjection) {
                        persistentProperty = entity.getIdentity();
                        propertyName = MongoEntityPersister.MONGO_ID_FIELD;
                    } else {
                        PropertyProjection pp = (PropertyProjection) projection;
                        persistentProperty = entity.getPropertyByName(pp.getPropertyName());
                        propertyName = getPropertyName(entity, persistentProperty.getName());
                    }
                    if (persistentProperty != null) {
                        populateMongoQuery(entity, query, criteria);

                        List propertyResults = null;
                        if (max > -1) {
                            // if there is a limit then we have to do a manual projection since the MongoDB driver doesn't support limits and distinct together
                            cursor = executeQueryAndApplyPagination(collection, query);
                            propertyResults = manualProjections
                                    .property(new MongoResultList(cursor, mongoEntityPersister), propertyName);
                        } else {

                            propertyResults = collection.distinct(propertyName, query);
                        }

                        if (persistentProperty instanceof ToOne) {
                            Association a = (Association) persistentProperty;
                            propertyResults = session.retrieveAll(a.getAssociatedEntity().getJavaClass(),
                                    propertyResults);
                        }

                        if (projectedResults.size() == 0 && projectionList.size() == 1) {
                            return propertyResults;
                        }
                        projectedResults.add(propertyResults);
                    } else {
                        throw new InvalidDataAccessResourceUsageException(
                                "Cannot use [" + projection.getClass().getSimpleName()
                                        + "] projection on non-existent property: " + propertyName);
                    }
                }
            }

            return projectedResults;
        }

        protected DBCursor executeQuery(final PersistentEntity entity, final Junction criteria,
                final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            if (criteria.isEmpty()) {
                cursor = executeQueryAndApplyPagination(collection, query);
            } else {
                populateMongoQuery(entity, query, criteria);
                cursor = executeQueryAndApplyPagination(collection, query);
            }

            if (queryArguments != null) {
                if (queryArguments.containsKey(HINT_ARGUMENT)) {
                    Object hint = queryArguments.get(HINT_ARGUMENT);
                    if (hint instanceof Map) {
                        cursor.hint(new BasicDBObject((Map) hint));
                    } else if (hint != null) {
                        cursor.hint(hint.toString());
                    }

                }
            }
            return cursor;
        }

        protected DBCursor executeQueryAndApplyPagination(final DBCollection collection, DBObject query) {
            final DBCursor cursor;
            cursor = collection.find(query);
            if (offset > 0) {
                cursor.skip(offset);
            }
            if (max > -1) {
                cursor.limit(max);
            }

            if (!orderBy.isEmpty()) {
                DBObject orderObject = new BasicDBObject();
                for (Order order : orderBy) {
                    String property = order.getProperty();
                    property = getPropertyName(entity, property);
                    orderObject.put(property, order.getDirection() == Order.Direction.DESC ? -1 : 1);
                }
                cursor.sort(orderObject);
            }

            return cursor;
        }
    });
}