Search in sources :

Example 6 with QueryContext

use of org.springframework.data.mongodb.core.QueryOperations.QueryContext in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doFind.

/**
 * Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified targetClass while
 * using sourceClass for mapping the query.
 *
 * @since 2.0
 */
<S, T> List<T> doFind(String collectionName, Document query, Document fields, Class<S> sourceClass, Class<T> targetClass, CursorPreparer preparer) {
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(sourceClass);
    EntityProjection<T, S> projection = operations.introspectProjection(targetClass, sourceClass);
    QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
    Document mappedFields = queryContext.getMappedFields(entity, projection);
    Document mappedQuery = queryContext.getMappedQuery(entity);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("find using query: %s fields: %s for class: %s in collection: %s", serializeToJsonSafely(mappedQuery), mappedFields, sourceClass, collectionName));
    }
    return executeFindMultiInternal(new FindCallback(mappedQuery, mappedFields, null), preparer, new ProjectingReadCallback<>(mongoConverter, projection, collectionName), collectionName);
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document)

Example 7 with QueryContext

use of org.springframework.data.mongodb.core.QueryOperations.QueryContext in project spring-data-mongodb by spring-projects.

the class MongoTemplate method findAndReplace.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.MongoOperations#findAndReplace(org.springframework.data.mongodb.core.query.Query, java.lang.Object, org.springframework.data.mongodb.core.FindAndReplaceOptions, java.lang.Class, java.lang.String, java.lang.Class)
	 */
@Override
public <S, T> T findAndReplace(Query query, S replacement, FindAndReplaceOptions options, Class<S> entityType, String collectionName, Class<T> resultType) {
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(replacement, "Replacement must not be null!");
    Assert.notNull(options, "Options must not be null! Use FindAndReplaceOptions#empty() instead.");
    Assert.notNull(entityType, "EntityType must not be null!");
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(resultType, "ResultType must not be null! Use Object.class instead.");
    Assert.isTrue(query.getLimit() <= 1, "Query must not define a limit other than 1 ore none!");
    Assert.isTrue(query.getSkip() <= 0, "Query must not define skip.");
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityType);
    QueryContext queryContext = queryOperations.createQueryContext(query);
    EntityProjection<T, S> projection = operations.introspectProjection(resultType, entityType);
    Document mappedQuery = queryContext.getMappedQuery(entity);
    Document mappedFields = queryContext.getMappedFields(entity, projection);
    Document mappedSort = queryContext.getMappedSort(entity);
    replacement = maybeCallBeforeConvert(replacement, collectionName);
    Document mappedReplacement = operations.forEntity(replacement).toMappedDocument(this.mongoConverter).getDocument();
    maybeEmitEvent(new BeforeSaveEvent<>(replacement, mappedReplacement, collectionName));
    maybeCallBeforeSave(replacement, mappedReplacement, collectionName);
    T saved = doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort, queryContext.getCollation(entityType).orElse(null), entityType, mappedReplacement, options, projection);
    if (saved != null) {
        maybeEmitEvent(new AfterSaveEvent<>(saved, mappedReplacement, collectionName));
        return maybeCallAfterSave(saved, mappedReplacement, collectionName);
    }
    return saved;
}
Also used : QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document)

Example 8 with QueryContext

use of org.springframework.data.mongodb.core.QueryOperations.QueryContext in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method findAndReplace.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndReplace(org.springframework.data.mongodb.core.query.Query, java.lang.Object, org.springframework.data.mongodb.core.FindAndReplaceOptions, java.lang.Class, java.lang.String, java.lang.Class)
	 */
@Override
public <S, T> Mono<T> findAndReplace(Query query, S replacement, FindAndReplaceOptions options, Class<S> entityType, String collectionName, Class<T> resultType) {
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(replacement, "Replacement must not be null!");
    Assert.notNull(options, "Options must not be null! Use FindAndReplaceOptions#empty() instead.");
    Assert.notNull(entityType, "Entity class must not be null!");
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(resultType, "ResultType must not be null! Use Object.class instead.");
    Assert.isTrue(query.getLimit() <= 1, "Query must not define a limit other than 1 ore none!");
    Assert.isTrue(query.getSkip() <= 0, "Query must not define skip.");
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityType);
    QueryContext queryContext = queryOperations.createQueryContext(query);
    EntityProjection<T, S> projection = operations.introspectProjection(resultType, entityType);
    Document mappedQuery = queryContext.getMappedQuery(entity);
    Document mappedFields = queryContext.getMappedFields(entity, projection);
    Document mappedSort = queryContext.getMappedSort(entity);
    return Mono.defer(() -> {
        PersistableEntityModel<S> pem = PersistableEntityModel.of(replacement, collectionName);
        maybeEmitEvent(new BeforeConvertEvent<>(pem.getSource(), pem.getCollection()));
        return maybeCallBeforeConvert(pem.getSource(), pem.getCollection()).map(pem::mutate).flatMap(it -> {
            PersistableEntityModel<S> mapped = it.addTargetDocument(operations.forEntity(it.getSource()).toMappedDocument(mongoConverter).getDocument());
            maybeEmitEvent(new BeforeSaveEvent(mapped.getSource(), mapped.getTarget(), mapped.getCollection()));
            return maybeCallBeforeSave(it.getSource(), mapped.getTarget(), mapped.getCollection()).map(potentiallyModified -> PersistableEntityModel.of(potentiallyModified, mapped.getTarget(), mapped.getCollection()));
        }).flatMap(it -> {
            Mono<T> afterFindAndReplace = doFindAndReplace(it.getCollection(), mappedQuery, mappedFields, mappedSort, queryContext.getCollation(entityType).orElse(null), entityType, it.getTarget(), options, projection);
            return afterFindAndReplace.flatMap(saved -> {
                maybeEmitEvent(new AfterSaveEvent<>(saved, it.getTarget(), it.getCollection()));
                return maybeCallAfterSave(saved, it.getTarget(), it.getCollection());
            });
        });
    });
}
Also used : Document(org.bson.Document) Arrays(java.util.Arrays) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) NumberUtils(org.springframework.util.NumberUtils) BsonUtils(org.springframework.data.mongodb.util.BsonUtils) Tuples(reactor.util.function.Tuples) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) ReactiveMongoDatabaseUtils(org.springframework.data.mongodb.ReactiveMongoDatabaseUtils) FullDocument(com.mongodb.client.model.changestream.FullDocument) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) CursorOption(org.springframework.data.mongodb.core.query.Meta.CursorOption) MongoJsonSchemaMapper(org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) MappingContextEvent(org.springframework.data.mapping.context.MappingContextEvent) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) CollectionUtils(org.springframework.util.CollectionUtils) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) LogFactory(org.apache.commons.logging.LogFactory) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) ApplicationContextAware(org.springframework.context.ApplicationContextAware) Validator(org.springframework.data.mongodb.core.validation.Validator) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) MappingContext(org.springframework.data.mapping.context.MappingContext) ArrayList(java.util.ArrayList) UpdateDefinition(org.springframework.data.mongodb.core.query.UpdateDefinition) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) NoOpDbRefResolver(org.springframework.data.mongodb.core.convert.NoOpDbRefResolver) ReactiveMongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.ReactiveMongoPersistentEntityIndexCreator) DbRefResolver(org.springframework.data.mongodb.core.convert.DbRefResolver) MappingException(org.springframework.data.mapping.MappingException) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Nullable(org.springframework.lang.Nullable) JsonSchemaMapper(org.springframework.data.mongodb.core.convert.JsonSchemaMapper) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) com.mongodb.client.model(com.mongodb.client.model) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) CountContext(org.springframework.data.mongodb.core.QueryOperations.CountContext) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) org.springframework.data.mongodb.core.mapping.event(org.springframework.data.mongodb.core.mapping.event) QueryMapper(org.springframework.data.mongodb.core.convert.QueryMapper) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) TypedAggregation(org.springframework.data.mongodb.core.aggregation.TypedAggregation) Mono(reactor.core.publisher.Mono) BeansException(org.springframework.beans.BeansException) MongoMappingEventPublisher(org.springframework.data.mongodb.core.index.MongoMappingEventPublisher) RelaxedTypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext) ResourceUtils(org.springframework.util.ResourceUtils) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) Collation(org.springframework.data.mongodb.core.query.Collation) EntityProjection(org.springframework.data.projection.EntityProjection) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) MapReduceOptions(org.springframework.data.mongodb.core.mapreduce.MapReduceOptions) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) AdaptibleEntity(org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity) CursorType(com.mongodb.CursorType) MongoWriter(org.springframework.data.mongodb.core.convert.MongoWriter) Meta(org.springframework.data.mongodb.core.query.Meta) ReactiveEntityCallbacks(org.springframework.data.mapping.callback.ReactiveEntityCallbacks) InsertOneResult(com.mongodb.client.result.InsertOneResult) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) MongoException(com.mongodb.MongoException) Collection(java.util.Collection) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) PersistentEntity(org.springframework.data.mapping.PersistentEntity) List(java.util.List) Optional(java.util.Optional) UpdateMapper(org.springframework.data.mongodb.core.convert.UpdateMapper) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) UpdateContext(org.springframework.data.mongodb.core.QueryOperations.UpdateContext) Metric(org.springframework.data.geo.Metric) ReadPreference(com.mongodb.ReadPreference) DataAccessException(org.springframework.dao.DataAccessException) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) ArrayFilter(org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter) Granularity(org.springframework.data.mongodb.core.timeseries.Granularity) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) AggregationDefinition(org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition) Subscriber(org.reactivestreams.Subscriber) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Iterator(java.util.Iterator) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) MapReducePublisher(com.mongodb.reactivestreams.client.MapReducePublisher) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) ClientSessionOptions(com.mongodb.ClientSessionOptions) DeleteResult(com.mongodb.client.result.DeleteResult) Log(org.apache.commons.logging.Log) GeoResult(org.springframework.data.geo.GeoResult) SessionSynchronization(org.springframework.data.mongodb.SessionSynchronization) WriteConcern(com.mongodb.WriteConcern) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument)

Example 9 with QueryContext

use of org.springframework.data.mongodb.core.QueryOperations.QueryContext in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doFind.

protected <S, T> List<T> doFind(String collectionName, Document query, Document fields, Class<S> entityClass, @Nullable CursorPreparer preparer, DocumentCallback<T> objectCallback) {
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
    QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields));
    Document mappedFields = queryContext.getMappedFields(entity, EntityProjection.nonProjecting(entityClass));
    Document mappedQuery = queryContext.getMappedQuery(entity);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("find using query: %s fields: %s for class: %s in collection: %s", serializeToJsonSafely(mappedQuery), mappedFields, entityClass, collectionName));
    }
    return executeFindMultiInternal(new FindCallback(mappedQuery, mappedFields, null), preparer != null ? preparer : CursorPreparer.NO_OP_PREPARER, objectCallback, collectionName);
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document)

Aggregations

Document (org.bson.Document)9 DistinctQueryContext (org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext)9 QueryContext (org.springframework.data.mongodb.core.QueryOperations.QueryContext)9 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)7 FullDocument (com.mongodb.client.model.changestream.FullDocument)4 ClientSessionOptions (com.mongodb.ClientSessionOptions)1 CursorType (com.mongodb.CursorType)1 MongoException (com.mongodb.MongoException)1 ReadPreference (com.mongodb.ReadPreference)1 WriteConcern (com.mongodb.WriteConcern)1 com.mongodb.client.model (com.mongodb.client.model)1 DeleteResult (com.mongodb.client.result.DeleteResult)1 InsertOneResult (com.mongodb.client.result.InsertOneResult)1 UpdateResult (com.mongodb.client.result.UpdateResult)1 AggregatePublisher (com.mongodb.reactivestreams.client.AggregatePublisher)1 ChangeStreamPublisher (com.mongodb.reactivestreams.client.ChangeStreamPublisher)1 ClientSession (com.mongodb.reactivestreams.client.ClientSession)1 DistinctPublisher (com.mongodb.reactivestreams.client.DistinctPublisher)1 FindPublisher (com.mongodb.reactivestreams.client.FindPublisher)1 MapReducePublisher (com.mongodb.reactivestreams.client.MapReducePublisher)1