org.springframework.data.mongodb.core.MongoTemplate.execute()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(188)

本文整理了Java中org.springframework.data.mongodb.core.MongoTemplate.execute()方法的一些代码示例,展示了MongoTemplate.execute()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MongoTemplate.execute()方法的具体详情如下:
包路径:org.springframework.data.mongodb.core.MongoTemplate
类名称:MongoTemplate
方法名:execute

MongoTemplate.execute介绍

[英]Internal method using callback to do queries against the datastore that requires reading a collection of objects. It will take the following steps

  1. Execute the given ConnectionCallback for a DBCursor.
  2. Prepare that DBCursor with the given CursorPreparer (will be skipped if CursorPrepareris null
  3. Iterate over the DBCursor and applies the given DocumentCallback to each of the Documents collecting the actual result List.
    [中]使用回调对需要读取对象集合的数据存储进行查询的内部方法。它将采取以下步骤
    1.为DBCursor执行给定的ConnectionCallback。
    1.使用给定的CursorPreparer准备DBCursor(如果CursorPreparer为空,将跳过
    1.迭代DBCursor并将给定的DocumentCallback应用于收集实际结果列表的每个文档。

代码示例

代码示例来源:origin: spring-projects/spring-data-mongodb

public Set<String> getCollectionNames() {
  return execute(new DbCallback<Set<String>>() {
    public Set<String> doInDB(MongoDatabase db) throws MongoException, DataAccessException {
      Set<String> result = new LinkedHashSet<>();
      for (String name : db.listCollectionNames()) {
        result.add(name);
      }
      return result;
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

return execute(collectionName, collection -> {

代码示例来源:origin: spring-projects/spring-data-mongodb

@Override
public Document executeCommand(final String jsonCommand) {
  Assert.hasText(jsonCommand, "JsonCommand must not be null nor empty!");
  return execute(new DbCallback<Document>() {
    public Document doInDB(MongoDatabase db) throws MongoException, DataAccessException {
      return db.runCommand(Document.parse(jsonCommand), Document.class);
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

public MongoCollection<Document> getCollection(final String collectionName) {
  Assert.notNull(collectionName, "CollectionName must not be null!");
  return execute(new DbCallback<MongoCollection<Document>>() {
    public MongoCollection<Document> doInDB(MongoDatabase db) throws MongoException, DataAccessException {
      return db.getCollection(collectionName, Document.class);
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

public boolean collectionExists(final String collectionName) {
  Assert.notNull(collectionName, "CollectionName must not be null!");
  return execute(new DbCallback<Boolean>() {
    public Boolean doInDB(MongoDatabase db) throws MongoException, DataAccessException {
      for (String name : db.listCollectionNames()) {
        if (name.equals(collectionName)) {
          return true;
        }
      }
      return false;
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

public void dropCollection(String collectionName) {
  Assert.notNull(collectionName, "CollectionName must not be null!");
  execute(collectionName, new CollectionCallback<Void>() {
    public Void doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
      collection.drop();
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Dropped collection [{}]",
            collection.getNamespace() != null ? collection.getNamespace().getCollectionName() : collectionName);
      }
      return null;
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

return execute(new DbCallback<MongoCollection<Document>>() {
  public MongoCollection<Document> doInDB(MongoDatabase db) throws MongoException, DataAccessException {

代码示例来源:origin: spring-projects/spring-data-mongodb

@Override
public Document executeCommand(final Document command) {
  Assert.notNull(command, "Command must not be null!");
  return execute(db -> db.runCommand(command, Document.class));
}

代码示例来源:origin: spring-projects/spring-data-mongodb

public <T> T execute(Class<?> entityClass, CollectionCallback<T> callback) {
  Assert.notNull(entityClass, "EntityClass must not be null!");
  return execute(operations.determineCollectionName(entityClass), callback);
}

代码示例来源:origin: spring-projects/spring-data-mongodb

protected <T> CloseableIterator<T> doStream(final Query query, final Class<?> entityType, final String collectionName,
    Class<T> returnType) {
  Assert.notNull(query, "Query must not be null!");
  Assert.notNull(entityType, "Entity type must not be null!");
  Assert.hasText(collectionName, "Collection name must not be null or empty!");
  Assert.notNull(returnType, "ReturnType must not be null!");
  return execute(collectionName, new CollectionCallback<CloseableIterator<T>>() {
    @Override
    public CloseableIterator<T> doInCollection(MongoCollection<Document> collection)
        throws MongoException, DataAccessException {
      MongoPersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(entityType);
      Document mappedFields = getMappedFieldsObject(query.getFieldsObject(), persistentEntity, returnType);
      Document mappedQuery = queryMapper.getMappedObject(query.getQueryObject(), persistentEntity);
      FindIterable<Document> cursor = new QueryCursorPreparer(query, entityType)
          .prepare(collection.find(mappedQuery, Document.class).projection(mappedFields));
      return new CloseableIterableCursorAdapter<>(cursor, exceptionTranslator,
          new ProjectingReadCallback<>(mongoConverter, entityType, returnType, collectionName));
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

@Override
public Document executeCommand(Document command, @Nullable ReadPreference readPreference) {
  Assert.notNull(command, "Command must not be null!");
  return execute(db -> readPreference != null //
      ? db.runCommand(command, readPreference, Document.class) //
      : db.runCommand(command, Document.class));
}

代码示例来源:origin: spring-projects/spring-data-mongodb

protected Object insertDocument(final String collectionName, final Document document, final Class<?> entityClass) {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Inserting Document containing fields: {} in collection: {}", document.keySet(), collectionName);
  }
  return execute(collectionName, new CollectionCallback<Object>() {
    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
      MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName,
          entityClass, document, null);
      WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
      if (writeConcernToUse == null) {
        collection.insertOne(document);
      } else {
        collection.withWriteConcern(writeConcernToUse).insertOne(document);
      }
      return operations.forEntity(document).getId();
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

protected long doCount(String collectionName, Document filter, CountOptions options) {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Executing count: {} in collection: {}", serializeToJsonSafely(filter), collectionName);
  }
  if (MongoDatabaseUtils.isTransactionActive(getMongoDbFactory())) {
    return execute(collectionName, collection -> collection.countDocuments(filter, options));
  }
  return execute(collectionName, collection -> collection.count(filter, options));
}

代码示例来源:origin: spring-projects/spring-data-mongodb

protected Object saveDocument(final String collectionName, final Document dbDoc, final Class<?> entityClass) {
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Saving Document containing fields: {}", dbDoc.keySet());
  }
  return execute(collectionName, new CollectionCallback<Object>() {
    public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
      MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass,
          dbDoc, null);
      WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
      MappedDocument mapped = MappedDocument.of(dbDoc);
      if (!mapped.hasId()) {
        if (writeConcernToUse == null) {
          collection.insertOne(dbDoc);
        } else {
          collection.withWriteConcern(writeConcernToUse).insertOne(dbDoc);
        }
      } else if (writeConcernToUse == null) {
        collection.replaceOne(mapped.getIdFilter(), dbDoc, new ReplaceOptions().upsert(true));
      } else {
        collection.withWriteConcern(writeConcernToUse).replaceOne(mapped.getIdFilter(), dbDoc,
            new ReplaceOptions().upsert(true));
      }
      return mapped.getId();
    }
  });
}

代码示例来源:origin: spring-projects/spring-data-mongodb

@Override
public boolean exists(Query query, @Nullable Class<?> entityClass, String collectionName) {
  if (query == null) {
    throw new InvalidDataAccessApiUsageException("Query passed in to exist can't be null");
  }
  Assert.notNull(collectionName, "CollectionName must not be null!");
  Document mappedQuery = queryMapper.getMappedObject(query.getQueryObject(), getPersistentEntity(entityClass));
  return execute(collectionName,
      new ExistsCallback(mappedQuery, query.getCollation().map(Collation::toMongoCollation).orElse(null)));
}

代码示例来源:origin: spring-projects/spring-data-mongodb

log.debug("Loading MongoDB data for {}", dbk);
mongoTemplate.execute(collName, new CollectionCallback<Object>() {
  public Object doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
    for (Document dbo : collection.find(dbk)) {

代码示例来源:origin: spring-projects/spring-data-mongodb

protected List<Object> insertDocumentList(final String collectionName, final List<Document> documents) {
  if (documents.isEmpty()) {
    return Collections.emptyList();
  }
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Inserting list of Documents containing {} items", documents.size());
  }
  execute(collectionName, collection -> {
    MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT_LIST, collectionName, null,
        null, null);
    WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
    if (writeConcernToUse == null) {
      collection.insertMany(documents);
    } else {
      collection.withWriteConcern(writeConcernToUse).insertMany(documents);
    }
    return null;
  });
  return MappedDocument.toIds(documents);
}

代码示例来源:origin: spring-projects/spring-data-mongodb

final Document queryObject = queryMapper.getMappedObject(query.getQueryObject(), entity);
return execute(collectionName, new CollectionCallback<DeleteResult>() {

代码示例来源:origin: spring-projects/spring-data-mongodb

MongoIterable<?> result = execute(collectionName, (collection) -> {

代码示例来源:origin: spring-projects/spring-data-mongodb

protected <O> CloseableIterator<O> aggregateStream(Aggregation aggregation, String collectionName,
    Class<O> outputType, @Nullable AggregationOperationContext context) {
  Assert.hasText(collectionName, "Collection name must not be null or empty!");
  Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
  Assert.notNull(outputType, "Output type must not be null!");
  Assert.isTrue(!aggregation.getOptions().isExplain(), "Can't use explain option with streaming!");
  AggregationUtil aggregationUtil = new AggregationUtil(queryMapper, mappingContext);
  AggregationOperationContext rootContext = aggregationUtil.prepareAggregationContext(aggregation, context);
  AggregationOptions options = aggregation.getOptions();
  List<Document> pipeline = aggregationUtil.createPipeline(aggregation, rootContext);
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("Streaming aggregation: {} in collection {}", serializeToJsonSafely(pipeline), collectionName);
  }
  ReadDocumentCallback<O> readCallback = new ReadDocumentCallback<>(mongoConverter, outputType, collectionName);
  return execute(collectionName, (CollectionCallback<CloseableIterator<O>>) collection -> {
    AggregateIterable<Document> cursor = collection.aggregate(pipeline, Document.class) //
        .allowDiskUse(options.isAllowDiskUse()) //
        .useCursor(true);
    if (options.getCursorBatchSize() != null) {
      cursor = cursor.batchSize(options.getCursorBatchSize());
    }
    if (options.getCollation().isPresent()) {
      cursor = cursor.collation(options.getCollation().map(Collation::toMongoCollation).get());
    }
    return new CloseableIterableCursorAdapter<>(cursor, exceptionTranslator, readCallback);
  });
}

相关文章