Search in sources :

Example 6 with MongoPersistentEntity

use of org.springframework.data.mongodb.core.mapping.MongoPersistentEntity in project spring-data-mongodb by spring-projects.

the class MongoTemplate method doUpdate.

protected UpdateResult doUpdate(final String collectionName, final Query query, final Update update, @Nullable final Class<?> entityClass, final boolean upsert, final boolean multi) {
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(update, "Update must not be null!");
    return execute(collectionName, new CollectionCallback<UpdateResult>() {

        public UpdateResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);
            increaseVersionForUpdateIfNecessary(entity, update);
            UpdateOptions opts = new UpdateOptions();
            opts.upsert(upsert);
            Document queryObj = new Document();
            if (query != null) {
                queryObj.putAll(queryMapper.getMappedObject(query.getQueryObject(), entity));
                query.getCollation().map(Collation::toMongoCollation).ifPresent(opts::collation);
            }
            Document updateObj = update == null ? new Document() : updateMapper.getMappedObject(update.getUpdateObject(), entity);
            if (multi && update.isIsolated() && !queryObj.containsKey("$isolated")) {
                queryObj.put("$isolated", 1);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}", serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName, entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            collection = writeConcernToUse != null ? collection.withWriteConcern(writeConcernToUse) : collection;
            if (!UpdateMapper.isUpdateObject(updateObj)) {
                return collection.replaceOne(queryObj, updateObj, opts);
            } else {
                if (multi) {
                    return collection.updateMany(queryObj, updateObj, opts);
                } else {
                    return collection.updateOne(queryObj, updateObj, opts);
                }
            }
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) WriteConcern(com.mongodb.WriteConcern) Document(org.bson.Document) Collation(org.springframework.data.mongodb.core.query.Collation) UpdateResult(com.mongodb.client.result.UpdateResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 7 with MongoPersistentEntity

use of org.springframework.data.mongodb.core.mapping.MongoPersistentEntity 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 8 with MongoPersistentEntity

use of org.springframework.data.mongodb.core.mapping.MongoPersistentEntity 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 9 with MongoPersistentEntity

use of org.springframework.data.mongodb.core.mapping.MongoPersistentEntity in project spring-data-mongodb by spring-projects.

the class MongoPersistentEntityIndexResolver method resolveIndexForEntity.

/**
 * Resolve the {@link IndexDefinition}s for given {@literal root} entity by traversing {@link MongoPersistentProperty}
 * scanning for index annotations {@link Indexed}, {@link CompoundIndex} and {@link GeospatialIndex}. The given
 * {@literal root} has therefore to be annotated with {@link Document}.
 *
 * @param root must not be null.
 * @return List of {@link IndexDefinitionHolder}. Will never be {@code null}.
 * @throws IllegalArgumentException in case of missing {@link Document} annotation marking root entities.
 */
public List<IndexDefinitionHolder> resolveIndexForEntity(final MongoPersistentEntity<?> root) {
    Assert.notNull(root, "Index cannot be resolved for given 'null' entity.");
    Document document = root.findAnnotation(Document.class);
    Assert.notNull(document, "Given entity is not collection root.");
    final List<IndexDefinitionHolder> indexInformation = new ArrayList<>();
    indexInformation.addAll(potentiallyCreateCompoundIndexDefinitions("", root.getCollection(), root));
    indexInformation.addAll(potentiallyCreateTextIndexDefinition(root));
    root.doWithProperties((PropertyHandler<MongoPersistentProperty>) property -> this.potentiallyAddIndexForProperty(root, property, indexInformation, new CycleGuard()));
    indexInformation.addAll(resolveIndexesForDbrefs("", root.getCollection(), root));
    return indexInformation;
}
Also used : Arrays(java.util.Arrays) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Association(org.springframework.data.mapping.Association) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) IncludeStrategy(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver.TextIndexIncludeOptions.IncludeStrategy) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) TypeInformation(org.springframework.data.util.TypeInformation) ArrayList(java.util.ArrayList) PropertyHandler(org.springframework.data.mapping.PropertyHandler) Document(org.springframework.data.mongodb.core.mapping.Document) HashSet(java.util.HashSet) AccessLevel(lombok.AccessLevel) MappingException(org.springframework.data.mapping.MappingException) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) Sort(org.springframework.data.domain.Sort) Nullable(org.springframework.lang.Nullable) PersistentProperty(org.springframework.data.mapping.PersistentProperty) TextIndexedFieldSpec(org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexedFieldSpec) Logger(org.slf4j.Logger) ClassUtils(org.springframework.util.ClassUtils) Iterator(java.util.Iterator) Path(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver.CycleGuard.Path) Collection(java.util.Collection) Set(java.util.Set) EqualsAndHashCode(lombok.EqualsAndHashCode) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) AssociationHandler(org.springframework.data.mapping.AssociationHandler) List(java.util.List) Collections(java.util.Collections) TextIndexDefinitionBuilder(org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) ArrayList(java.util.ArrayList) Document(org.springframework.data.mongodb.core.mapping.Document)

Example 10 with MongoPersistentEntity

use of org.springframework.data.mongodb.core.mapping.MongoPersistentEntity in project spring-data-mongodb by spring-projects.

the class ReactivePerformanceTests method setUp.

@Before
public void setUp() throws Exception {
    mongo = MongoClients.create();
    SimpleReactiveMongoDatabaseFactory mongoDbFactory = new SimpleReactiveMongoDatabaseFactory(this.mongo, DATABASE_NAME);
    MongoMappingContext context = new MongoMappingContext();
    context.setInitialEntitySet(Collections.singleton(Person.class));
    context.afterPropertiesSet();
    converter = new MappingMongoConverter(new DbRefResolver() {

        @Override
        public Object resolveDbRef(MongoPersistentProperty property, DBRef dbref, DbRefResolverCallback callback, DbRefProxyHandler proxyHandler) {
            return null;
        }

        @Override
        public DBRef createDbRef(org.springframework.data.mongodb.core.mapping.DBRef annotation, MongoPersistentEntity<?> entity, Object id) {
            return null;
        }

        @Override
        public Document fetch(DBRef dbRef) {
            return null;
        }

        @Override
        public List<Document> bulkFetch(List<DBRef> dbRefs) {
            return null;
        }
    }, context);
    operations = new ReactiveMongoTemplate(mongoDbFactory, converter);
    ReactiveMongoRepositoryFactory factory = new ReactiveMongoRepositoryFactory(operations);
    repository = factory.getRepository(ReactivePersonRepository.class);
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) DbRefResolverCallback(org.springframework.data.mongodb.core.convert.DbRefResolverCallback) DBRef(com.mongodb.DBRef) DbRefResolver(org.springframework.data.mongodb.core.convert.DbRefResolver) Document(org.bson.Document) SimpleReactiveMongoDatabaseFactory(org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory) ReactiveMongoTemplate(org.springframework.data.mongodb.core.ReactiveMongoTemplate) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) ReactiveMongoRepositoryFactory(org.springframework.data.mongodb.repository.support.ReactiveMongoRepositoryFactory) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) BasicDBObject(com.mongodb.BasicDBObject) BasicDBList(com.mongodb.BasicDBList) DbRefProxyHandler(org.springframework.data.mongodb.core.convert.DbRefProxyHandler) Before(org.junit.Before)

Aggregations

MongoPersistentEntity (org.springframework.data.mongodb.core.mapping.MongoPersistentEntity)10 MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)9 Document (org.bson.Document)7 MongoMappingContext (org.springframework.data.mongodb.core.mapping.MongoMappingContext)7 Assert (org.springframework.util.Assert)6 ClassUtils (org.springframework.util.ClassUtils)6 StringUtils (org.springframework.util.StringUtils)6 UpdateResult (com.mongodb.client.result.UpdateResult)5 Entry (java.util.Map.Entry)5 Bson (org.bson.conversions.Bson)5 DeleteResult (com.mongodb.client.result.DeleteResult)4 ClientSession (com.mongodb.session.ClientSession)4 JSONParseException (com.mongodb.util.JSONParseException)4 java.util (java.util)4 Collectors (java.util.stream.Collectors)4 RequiredArgsConstructor (lombok.RequiredArgsConstructor)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 DataAccessException (org.springframework.dao.DataAccessException)4 InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)4