Search in sources :

Example 1 with AfterDeleteEvent

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

the class MongoTemplate method doRemove.

protected <T> DeleteResult doRemove(final String collectionName, final Query query, @Nullable final Class<T> entityClass) {
    Assert.notNull(query, "Query must not be null!");
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    final MongoPersistentEntity<?> entity = getPersistentEntity(entityClass);
    final Document queryObject = queryMapper.getMappedObject(query.getQueryObject(), entity);
    return execute(collectionName, new CollectionCallback<DeleteResult>() {

        public DeleteResult doInCollection(MongoCollection<Document> collection) throws MongoException, DataAccessException {
            maybeEmitEvent(new BeforeDeleteEvent<T>(queryObject, entityClass, collectionName));
            Document removeQuery = queryObject;
            DeleteOptions options = new DeleteOptions();
            query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation);
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.REMOVE, collectionName, entityClass, null, queryObject);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            DeleteResult dr = null;
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Remove using query: {} in collection: {}.", new Object[] { serializeToJsonSafely(removeQuery), collectionName });
            }
            if (query.getLimit() > 0 || query.getSkip() > 0) {
                MongoCursor<Document> cursor = new QueryCursorPreparer(query, entityClass).prepare(collection.find(removeQuery).projection(new Document(ID_FIELD, 1))).iterator();
                Set<Object> ids = new LinkedHashSet<>();
                while (cursor.hasNext()) {
                    ids.add(cursor.next().get(ID_FIELD));
                }
                removeQuery = new Document(ID_FIELD, new Document("$in", ids));
            }
            if (writeConcernToUse == null) {
                dr = collection.deleteMany(removeQuery, options);
            } else {
                dr = collection.withWriteConcern(writeConcernToUse).deleteMany(removeQuery, options);
            }
            maybeEmitEvent(new AfterDeleteEvent<T>(queryObject, entityClass, collectionName));
            return dr;
        }
    });
}
Also used : MongoException(com.mongodb.MongoException) Document(org.bson.Document) BeforeDeleteEvent(org.springframework.data.mongodb.core.mapping.event.BeforeDeleteEvent) Collation(org.springframework.data.mongodb.core.query.Collation) AfterDeleteEvent(org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent) WriteConcern(com.mongodb.WriteConcern) MongoCursor(com.mongodb.client.MongoCursor) DeleteResult(com.mongodb.client.result.DeleteResult) DataAccessException(org.springframework.dao.DataAccessException)

Example 2 with AfterDeleteEvent

use of org.springframework.data.mongodb.core.mapping.event.AfterDeleteEvent 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)

Aggregations

DeleteResult (com.mongodb.client.result.DeleteResult)2 Document (org.bson.Document)2 com.mongodb (com.mongodb)1 MongoException (com.mongodb.MongoException)1 WriteConcern (com.mongodb.WriteConcern)1 MongoCursor (com.mongodb.client.MongoCursor)1 CountOptions (com.mongodb.client.model.CountOptions)1 CreateCollectionOptions (com.mongodb.client.model.CreateCollectionOptions)1 DeleteOptions (com.mongodb.client.model.DeleteOptions)1 Filters (com.mongodb.client.model.Filters)1 FindOneAndDeleteOptions (com.mongodb.client.model.FindOneAndDeleteOptions)1 FindOneAndUpdateOptions (com.mongodb.client.model.FindOneAndUpdateOptions)1 ReturnDocument (com.mongodb.client.model.ReturnDocument)1 UpdateOptions (com.mongodb.client.model.UpdateOptions)1 ValidationOptions (com.mongodb.client.model.ValidationOptions)1 FullDocument (com.mongodb.client.model.changestream.FullDocument)1 UpdateResult (com.mongodb.client.result.UpdateResult)1 AggregatePublisher (com.mongodb.reactivestreams.client.AggregatePublisher)1 ChangeStreamPublisher (com.mongodb.reactivestreams.client.ChangeStreamPublisher)1 DistinctPublisher (com.mongodb.reactivestreams.client.DistinctPublisher)1