Search in sources :

Example 11 with Nullable

use of org.springframework.lang.Nullable in project spring-data-mongodb by spring-projects.

the class MongoTemplate method findById.

@Nullable
@Override
public <T> T findById(Object id, Class<T> entityClass, String collectionName) {
    Assert.notNull(id, "Id must not be null!");
    Assert.notNull(entityClass, "EntityClass must not be null!");
    Assert.notNull(collectionName, "CollectionName must not be null!");
    MongoPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(entityClass);
    String idKey = ID_FIELD;
    if (persistentEntity != null) {
        if (persistentEntity.getIdProperty() != null) {
            idKey = persistentEntity.getIdProperty().getName();
        }
    }
    return doFindOne(collectionName, new Document(idKey, id), new Document(), entityClass);
}
Also used : Document(org.bson.Document) Nullable(org.springframework.lang.Nullable)

Example 12 with Nullable

use of org.springframework.lang.Nullable in project spring-data-mongodb by spring-projects.

the class MongoTemplate method aggregateStream.

@SuppressWarnings("ConstantConditions")
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!");
    AggregationOperationContext rootContext = context == null ? Aggregation.DEFAULT_CONTEXT : context;
    AggregationOptions options = aggregation.getOptions();
    List<Document> pipeline = aggregation.toPipeline(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.iterator(), exceptionTranslator, readCallback);
    });
}
Also used : Document(org.bson.Document) PropertyReferenceException(org.springframework.data.mapping.PropertyReferenceException) MongoDatabase(com.mongodb.client.MongoDatabase) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) Fields(org.springframework.data.mongodb.core.aggregation.Fields) ClientSession(com.mongodb.session.ClientSession) BulkOperationContext(org.springframework.data.mongodb.core.DefaultBulkOperations.BulkOperationContext) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) MapReduceResults(org.springframework.data.mongodb.core.mapreduce.MapReduceResults) Resource(org.springframework.core.io.Resource) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NonNull(lombok.NonNull) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) Mongo(com.mongodb.Mongo) AggregateIterable(com.mongodb.client.AggregateIterable) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) Cursor(com.mongodb.Cursor) MongoDbFactory(org.springframework.data.mongodb.MongoDbFactory) CollectionUtils(org.springframework.util.CollectionUtils) PropertyPath(org.springframework.data.mapping.PropertyPath) Id(org.springframework.data.annotation.Id) SpelAwareProxyProjectionFactory(org.springframework.data.projection.SpelAwareProxyProjectionFactory) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) java.util(java.util) Validator(org.springframework.data.mongodb.core.validation.Validator) IndexOperationsProvider(org.springframework.data.mongodb.core.index.IndexOperationsProvider) MongoCollection(com.mongodb.client.MongoCollection) GroupByResults(org.springframework.data.mongodb.core.mapreduce.GroupByResults) MappingContext(org.springframework.data.mapping.context.MappingContext) Bson(org.bson.conversions.Bson) ProjectionInformation(org.springframework.data.projection.ProjectionInformation) AccessLevel(lombok.AccessLevel) MappingException(org.springframework.data.mapping.MappingException) ConvertingPropertyAccessor(org.springframework.data.mapping.model.ConvertingPropertyAccessor) Nullable(org.springframework.lang.Nullable) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) com.mongodb.client.model(com.mongodb.client.model) ConversionService(org.springframework.core.convert.ConversionService) BeforeConvertEvent(org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent) AfterConvertEvent(org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent) BeforeSaveEvent(org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent) ObjectUtils(org.springframework.util.ObjectUtils) TypedAggregation(org.springframework.data.mongodb.core.aggregation.TypedAggregation) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) MongoMappingEventPublisher(org.springframework.data.mongodb.core.index.MongoMappingEventPublisher) Criteria(org.springframework.data.mongodb.core.query.Criteria) ResourceUtils(org.springframework.util.ResourceUtils) DistinctIterable(com.mongodb.client.DistinctIterable) DBCursor(com.mongodb.DBCursor) MongoMappingEvent(org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent) MongoIterable(com.mongodb.client.MongoIterable) org.springframework.data.mongodb.core.convert(org.springframework.data.mongodb.core.convert) JSONParseException(com.mongodb.util.JSONParseException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) CloseableIterator(org.springframework.data.util.CloseableIterator) Collation(org.springframework.data.mongodb.core.query.Collation) MongoClientVersion(org.springframework.data.mongodb.util.MongoClientVersion) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) 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) Pair(org.springframework.data.util.Pair) MapReduceIterable(com.mongodb.client.MapReduceIterable) Update(org.springframework.data.mongodb.core.query.Update) StreamUtils(org.springframework.data.util.StreamUtils) Meta(org.springframework.data.mongodb.core.query.Meta) ResourceLoader(org.springframework.core.io.ResourceLoader) MongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) MongoException(com.mongodb.MongoException) ApplicationListener(org.springframework.context.ApplicationListener) AggregationResults(org.springframework.data.mongodb.core.aggregation.AggregationResults) Collectors(java.util.stream.Collectors) FindIterable(com.mongodb.client.FindIterable) Entry(java.util.Map.Entry) Codec(org.bson.codecs.Codec) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) 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) BulkMode(org.springframework.data.mongodb.core.BulkOperations.BulkMode) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) Distance(org.springframework.data.geo.Distance) IndexOperations(org.springframework.data.mongodb.core.index.IndexOperations) EntityReader(org.springframework.data.convert.EntityReader) AfterLoadEvent(org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent) MongoCursor(com.mongodb.client.MongoCursor) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) GroupBy(org.springframework.data.mongodb.core.mapreduce.GroupBy) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Logger(org.slf4j.Logger) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) ConnectionCallback(org.springframework.jca.cci.core.ConnectionCallback) DBCollection(com.mongodb.DBCollection) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) TimeUnit(java.util.concurrent.TimeUnit) AfterSaveEvent(org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent) ClientSessionOptions(com.mongodb.ClientSessionOptions) GeoResults(org.springframework.data.geo.GeoResults) MongoClient(com.mongodb.MongoClient) DeleteResult(com.mongodb.client.result.DeleteResult) AllArgsConstructor(lombok.AllArgsConstructor) GeoResult(org.springframework.data.geo.GeoResult) WriteConcern(com.mongodb.WriteConcern) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) CloseableIterator(org.springframework.data.util.CloseableIterator) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) Document(org.bson.Document) AggregateIterable(com.mongodb.client.AggregateIterable) Collation(org.springframework.data.mongodb.core.query.Collation)

Example 13 with Nullable

use of org.springframework.lang.Nullable in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method doUpdate.

protected Mono<UpdateResult> doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class<?> entityClass, final boolean upsert, final boolean multi) {
    MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
    Flux<UpdateResult> result = execute(collectionName, collection -> {
        increaseVersionForUpdateIfNecessary(entity, update);
        Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
        Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Calling update using query: %s and update: %s in collection: %s", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName));
        }
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
        UpdateOptions updateOptions = new UpdateOptions().upsert(upsert);
        query.getCollation().map(Collation::toMongoCollation).ifPresent(updateOptions::collation);
        if (!UpdateMapper.isUpdateObject(updateObj)) {
            return collectionToUse.replaceOne(queryObj, updateObj, updateOptions);
        }
        if (multi) {
            return collectionToUse.updateMany(queryObj, updateObj, updateOptions);
        }
        return collectionToUse.updateOne(queryObj, updateObj, updateOptions);
    }).doOnNext(updateResult -> {
        if (entity != null && entity.hasVersionProperty() && !multi) {
            if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
                Document queryObj = query == null ? new Document() : queryMapper.getMappedObject(query.getQueryObject(), entity);
                Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
                if (dbObjectContainsVersionProperty(queryObj, entity))
                    throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: " + updateObj.toString() + " to collection " + collectionName);
            }
        }
    });
    return result.next();
}
Also used : Document(org.bson.Document) PropertyReferenceException(org.springframework.data.mapping.PropertyReferenceException) DeleteOptions(com.mongodb.client.model.DeleteOptions) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ClientSession(com.mongodb.session.ClientSession) FullDocument(com.mongodb.client.model.changestream.FullDocument) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) UpdateOptions(com.mongodb.client.model.UpdateOptions) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NonNull(lombok.NonNull) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) MongoDbFactory(org.springframework.data.mongodb.MongoDbFactory) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) PropertyPath(org.springframework.data.mapping.PropertyPath) Id(org.springframework.data.annotation.Id) SpelAwareProxyProjectionFactory(org.springframework.data.projection.SpelAwareProxyProjectionFactory) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) java.util(java.util) Validator(org.springframework.data.mongodb.core.validation.Validator) MappingContext(org.springframework.data.mapping.context.MappingContext) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CountOptions(com.mongodb.client.model.CountOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) Filters(com.mongodb.client.model.Filters) ProjectionInformation(org.springframework.data.projection.ProjectionInformation) MappingException(org.springframework.data.mapping.MappingException) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) ConvertingPropertyAccessor(org.springframework.data.mapping.model.ConvertingPropertyAccessor) Nullable(org.springframework.lang.Nullable) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) Success(com.mongodb.reactivestreams.client.Success) ConversionService(org.springframework.core.convert.ConversionService) BeforeConvertEvent(org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) AfterConvertEvent(org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent) BeforeSaveEvent(org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) 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) Criteria(org.springframework.data.mongodb.core.query.Criteria) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) MongoMappingEvent(org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent) org.springframework.data.mongodb.core.convert(org.springframework.data.mongodb.core.convert) JSONParseException(com.mongodb.util.JSONParseException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) Collation(org.springframework.data.mongodb.core.query.Collation) MongoClientVersion(org.springframework.data.mongodb.util.MongoClientVersion) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) com.mongodb(com.mongodb) Pair(org.springframework.data.util.Pair) Update(org.springframework.data.mongodb.core.query.Update) MongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) ReturnDocument(com.mongodb.client.model.ReturnDocument) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) Entry(java.util.Map.Entry) Codec(org.bson.codecs.Codec) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) Metric(org.springframework.data.geo.Metric) 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) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) AfterLoadEvent(org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent) FindOneAndDeleteOptions(com.mongodb.client.model.FindOneAndDeleteOptions) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) ValidationOptions(com.mongodb.client.model.ValidationOptions) Nonnull(javax.annotation.Nonnull) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Logger(org.slf4j.Logger) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) IndexOperationsAdapter(org.springframework.data.mongodb.core.index.IndexOperationsAdapter) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) Consumer(java.util.function.Consumer) AfterSaveEvent(org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) DeleteResult(com.mongodb.client.result.DeleteResult) GeoResult(org.springframework.data.geo.GeoResult) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) ReturnDocument(com.mongodb.client.model.ReturnDocument) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions)

Example 14 with Nullable

use of org.springframework.lang.Nullable in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method doRemove.

protected <T> Mono<DeleteResult> doRemove(String collectionName, Query query, @Nullable Class<T> entityClass) {
    if (query == null) {
        throw new InvalidDataAccessApiUsageException("Query passed in to remove can't be null!");
    }
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    final Document queryObject = query.getQueryObject();
    final MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
    return execute(collectionName, collection -> {
        Document removeQuey = queryMapper.getMappedObject(queryObject, entity);
        maybeEmitEvent(new BeforeDeleteEvent<T>(removeQuey, entityClass, collectionName));
        MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, removeQuey);
        final DeleteOptions deleteOptions = new DeleteOptions();
        query.getCollation().map(Collation::toMongoCollation).ifPresent(deleteOptions::collation);
        WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
        MongoCollection<Document> collectionToUse = prepareCollection(collection, writeConcernToUse);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remove using query: {} in collection: {}.", new Object[] { serializeToJsonSafely(removeQuey), collectionName });
        }
        if (query.getLimit() > 0 || query.getSkip() > 0) {
            FindPublisher<Document> cursor = new QueryFindPublisherPreparer(query, entityClass).prepare(// 
            collection.find(removeQuey)).projection(new Document(ID_FIELD, 1));
            return // 
            Flux.from(cursor).map(// 
            doc -> doc.get(ID_FIELD)).collectList().flatMapMany(val -> {
                return collectionToUse.deleteMany(new Document(ID_FIELD, new Document("$in", val)), deleteOptions);
            });
        } else {
            return collectionToUse.deleteMany(removeQuey, deleteOptions);
        }
    }).doOnNext(deleteResult -> maybeEmitEvent(new AfterDeleteEvent<T>(queryObject, entityClass, collectionName))).next();
}
Also used : Document(org.bson.Document) PropertyReferenceException(org.springframework.data.mapping.PropertyReferenceException) DeleteOptions(com.mongodb.client.model.DeleteOptions) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ClientSession(com.mongodb.session.ClientSession) FullDocument(com.mongodb.client.model.changestream.FullDocument) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) UpdateOptions(com.mongodb.client.model.UpdateOptions) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NonNull(lombok.NonNull) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) MongoDbFactory(org.springframework.data.mongodb.MongoDbFactory) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) PropertyPath(org.springframework.data.mapping.PropertyPath) Id(org.springframework.data.annotation.Id) SpelAwareProxyProjectionFactory(org.springframework.data.projection.SpelAwareProxyProjectionFactory) ApplicationContextAware(org.springframework.context.ApplicationContextAware) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) java.util(java.util) Validator(org.springframework.data.mongodb.core.validation.Validator) MappingContext(org.springframework.data.mapping.context.MappingContext) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CountOptions(com.mongodb.client.model.CountOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) Filters(com.mongodb.client.model.Filters) ProjectionInformation(org.springframework.data.projection.ProjectionInformation) MappingException(org.springframework.data.mapping.MappingException) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) ConvertingPropertyAccessor(org.springframework.data.mapping.model.ConvertingPropertyAccessor) Nullable(org.springframework.lang.Nullable) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) Success(com.mongodb.reactivestreams.client.Success) ConversionService(org.springframework.core.convert.ConversionService) BeforeConvertEvent(org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) AfterConvertEvent(org.springframework.data.mongodb.core.mapping.event.AfterConvertEvent) BeforeSaveEvent(org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) 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) Criteria(org.springframework.data.mongodb.core.query.Criteria) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) MongoMappingEvent(org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent) org.springframework.data.mongodb.core.convert(org.springframework.data.mongodb.core.convert) JSONParseException(com.mongodb.util.JSONParseException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) Collation(org.springframework.data.mongodb.core.query.Collation) MongoClientVersion(org.springframework.data.mongodb.util.MongoClientVersion) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) com.mongodb(com.mongodb) Pair(org.springframework.data.util.Pair) Update(org.springframework.data.mongodb.core.query.Update) MongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) ReturnDocument(com.mongodb.client.model.ReturnDocument) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) Entry(java.util.Map.Entry) Codec(org.bson.codecs.Codec) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) Metric(org.springframework.data.geo.Metric) 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) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) AfterLoadEvent(org.springframework.data.mongodb.core.mapping.event.AfterLoadEvent) FindOneAndDeleteOptions(com.mongodb.client.model.FindOneAndDeleteOptions) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) ValidationOptions(com.mongodb.client.model.ValidationOptions) Nonnull(javax.annotation.Nonnull) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Logger(org.slf4j.Logger) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) IndexOperationsAdapter(org.springframework.data.mongodb.core.index.IndexOperationsAdapter) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) Consumer(java.util.function.Consumer) AfterSaveEvent(org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) DeleteResult(com.mongodb.client.result.DeleteResult) GeoResult(org.springframework.data.geo.GeoResult) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) DeleteOptions(com.mongodb.client.model.DeleteOptions) FindOneAndDeleteOptions(com.mongodb.client.model.FindOneAndDeleteOptions) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) ReturnDocument(com.mongodb.client.model.ReturnDocument) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException)

Example 15 with Nullable

use of org.springframework.lang.Nullable in project spring-data-mongodb by spring-projects.

the class QueryMapper method getMappedValue.

/**
 * Returns the mapped value for the given source object assuming it's a value for the given
 * {@link MongoPersistentProperty}.
 *
 * @param value the source object to be mapped
 * @param property the property the value is a value for
 * @param newKey the key the value will be bound to eventually
 * @return
 */
@Nullable
@SuppressWarnings("unchecked")
protected Object getMappedValue(Field documentField, Object value) {
    if (documentField.isIdField()) {
        if (isDBObject(value)) {
            DBObject valueDbo = (DBObject) value;
            Document resultDbo = new Document(valueDbo.toMap());
            if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) {
                String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
                List<Object> ids = new ArrayList<Object>();
                for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                    ids.add(convertId(id));
                }
                resultDbo.put(inKey, ids);
            } else if (valueDbo.containsField("$ne")) {
                resultDbo.put("$ne", convertId(valueDbo.get("$ne")));
            } else {
                return getMappedObject(resultDbo, Optional.empty());
            }
            return resultDbo;
        } else if (isDocument(value)) {
            Document valueDbo = (Document) value;
            Document resultDbo = new Document(valueDbo);
            if (valueDbo.containsKey("$in") || valueDbo.containsKey("$nin")) {
                String inKey = valueDbo.containsKey("$in") ? "$in" : "$nin";
                List<Object> ids = new ArrayList<Object>();
                for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                    ids.add(convertId(id));
                }
                resultDbo.put(inKey, ids);
            } else if (valueDbo.containsKey("$ne")) {
                resultDbo.put("$ne", convertId(valueDbo.get("$ne")));
            } else {
                return getMappedObject(resultDbo, Optional.empty());
            }
            return resultDbo;
        } else {
            return convertId(value);
        }
    }
    if (isNestedKeyword(value)) {
        return getMappedKeyword(new Keyword((Bson) value), documentField.getPropertyEntity());
    }
    if (isAssociationConversionNecessary(documentField, value)) {
        return convertAssociation(value, documentField);
    }
    return convertSimpleOrDocument(value, documentField.getPropertyEntity());
}
Also used : ArrayList(java.util.ArrayList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) BasicDBList(com.mongodb.BasicDBList) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) NestedDocument(org.springframework.data.mongodb.core.convert.MappingMongoConverter.NestedDocument) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Bson(org.bson.conversions.Bson) Nullable(org.springframework.lang.Nullable)

Aggregations

Nullable (org.springframework.lang.Nullable)18 Document (org.bson.Document)11 BasicDBObject (com.mongodb.BasicDBObject)5 Entry (java.util.Map.Entry)5 BsonValue (org.bson.BsonValue)5 MappingException (org.springframework.data.mapping.MappingException)5 PersistentPropertyAccessor (org.springframework.data.mapping.PersistentPropertyAccessor)5 ConvertingPropertyAccessor (org.springframework.data.mapping.model.ConvertingPropertyAccessor)5 DBObject (com.mongodb.DBObject)4 DeleteResult (com.mongodb.client.result.DeleteResult)4 UpdateResult (com.mongodb.client.result.UpdateResult)4 ClientSession (com.mongodb.session.ClientSession)4 JSONParseException (com.mongodb.util.JSONParseException)4 Bson (org.bson.conversions.Bson)4 BasicDBList (com.mongodb.BasicDBList)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 NonNull (lombok.NonNull)3 RequiredArgsConstructor (lombok.RequiredArgsConstructor)3 Codec (org.bson.codecs.Codec)3