Search in sources :

Example 26 with InvalidDataAccessApiUsageException

use of org.springframework.dao.InvalidDataAccessApiUsageException in project spring-data-mongodb by spring-projects.

the class MongoTemplate method assertUpdateableIdIfNotSet.

private void assertUpdateableIdIfNotSet(Object value) {
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(value.getClass());
    if (entity != null && entity.hasIdProperty()) {
        MongoPersistentProperty property = entity.getRequiredIdProperty();
        Object propertyValue = entity.getPropertyAccessor(value).getProperty(property);
        if (propertyValue != null) {
            return;
        }
        if (!MongoSimpleTypes.AUTOGENERATED_ID_TYPES.contains(property.getType())) {
            throw new InvalidDataAccessApiUsageException(String.format("Cannot autogenerate id of type %s for entity of type %s!", property.getType().getName(), value.getClass().getName()));
        }
    }
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException)

Example 27 with InvalidDataAccessApiUsageException

use of org.springframework.dao.InvalidDataAccessApiUsageException in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method assertUpdateableIdIfNotSet.

private void assertUpdateableIdIfNotSet(Object value) {
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(value.getClass());
    if (entity != null && entity.hasIdProperty()) {
        MongoPersistentProperty property = entity.getRequiredIdProperty();
        Object propertyValue = entity.getPropertyAccessor(value).getProperty(property);
        if (propertyValue != null) {
            return;
        }
        if (!MongoSimpleTypes.AUTOGENERATED_ID_TYPES.contains(property.getType())) {
            throw new InvalidDataAccessApiUsageException(String.format("Cannot autogenerate id of type %s for entity of type %s!", property.getType().getName(), value.getClass().getName()));
        }
    }
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException)

Example 28 with InvalidDataAccessApiUsageException

use of org.springframework.dao.InvalidDataAccessApiUsageException 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 29 with InvalidDataAccessApiUsageException

use of org.springframework.dao.InvalidDataAccessApiUsageException in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method geoNear.

protected <T> Flux<GeoResult<T>> geoNear(NearQuery near, Class<?> entityClass, String collectionName, Class<T> returnType) {
    if (near == null) {
        throw new InvalidDataAccessApiUsageException("NearQuery must not be null!");
    }
    if (entityClass == null) {
        throw new InvalidDataAccessApiUsageException("Entity class must not be null!");
    }
    String collection = StringUtils.hasText(collectionName) ? collectionName : determineCollectionName(entityClass);
    Document nearDbObject = near.toDocument();
    Document command = new Document("geoNear", collection);
    command.putAll(nearDbObject);
    return Flux.defer(() -> {
        if (nearDbObject.containsKey("query")) {
            Document query = (Document) nearDbObject.get("query");
            command.put("query", queryMapper.getMappedObject(query, getPersistentEntity(entityClass)));
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Executing geoNear using: {} for class: {} in collection: {}", serializeToJsonSafely(command), entityClass, collectionName);
        }
        GeoNearResultDbObjectCallback<T> callback = new GeoNearResultDbObjectCallback<T>(new ProjectingReadCallback<>(mongoConverter, entityClass, returnType, collectionName), near.getMetric());
        return executeCommand(command, this.readPreference).flatMapMany(document -> {
            List<Document> l = document.get("results", List.class);
            if (l == null) {
                return Flux.empty();
            }
            return Flux.fromIterable(l);
        }).skip(near.getSkip() != null ? near.getSkip() : 0).map(callback::doWith);
    });
}
Also used : InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument) ReturnDocument(com.mongodb.client.model.ReturnDocument)

Aggregations

InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)29 Document (org.bson.Document)6 Test (org.junit.Test)6 SQLException (java.sql.SQLException)5 DataAccessException (org.springframework.dao.DataAccessException)5 SqlParameter (org.springframework.jdbc.core.SqlParameter)4 Connection (java.sql.Connection)3 ResultSet (java.sql.ResultSet)3 ArrayList (java.util.ArrayList)3 MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)3 Filters (com.mongodb.client.model.Filters)2 ReturnDocument (com.mongodb.client.model.ReturnDocument)2 FullDocument (com.mongodb.client.model.changestream.FullDocument)2 IOException (java.io.IOException)2 Serializable (java.io.Serializable)2 Method (java.lang.reflect.Method)2 PreparedStatement (java.sql.PreparedStatement)2 HashMap (java.util.HashMap)2 List (java.util.List)2 OptimisticLockingFailureException (org.springframework.dao.OptimisticLockingFailureException)2