Search in sources :

Example 1 with Nullable

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

the class MongoTemplate method count.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.MongoOperations#count(org.springframework.data.mongodb.core.query.Query, java.lang.Class, java.lang.String)
	 */
public long count(Query query, @Nullable Class<?> entityClass, String collectionName) {
    Assert.notNull(query, "Query must not be null!");
    Assert.hasText(collectionName, "Collection name must not be null or empty!");
    CountOptions options = new CountOptions();
    query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation);
    Document document = queryMapper.getMappedObject(query.getQueryObject(), Optional.ofNullable(entityClass).map(it -> mappingContext.getPersistentEntity(entityClass)));
    return execute(collectionName, collection -> collection.count(document, options));
}
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) Document(org.bson.Document)

Example 2 with Nullable

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

the class DocumentAccessor method get.

/**
 * Returns the value the given {@link MongoPersistentProperty} refers to. By default this will be a direct field but
 * the method will also transparently resolve nested values the {@link MongoPersistentProperty} might refer to through
 * a path expression in the field name metadata.
 *
 * @param property must not be {@literal null}.
 * @return
 */
@Nullable
public Object get(MongoPersistentProperty property) {
    String fieldName = property.getFieldName();
    if (!fieldName.contains(".")) {
        return BsonUtils.asMap(this.document).get(fieldName);
    }
    Iterator<String> parts = Arrays.asList(fieldName.split("\\.")).iterator();
    Map<String, Object> source = BsonUtils.asMap(this.document);
    Object result = null;
    while (source != null && parts.hasNext()) {
        result = source.get(parts.next());
        if (parts.hasNext()) {
            source = getAsMap(result);
        }
    }
    return result;
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Nullable(org.springframework.lang.Nullable)

Example 3 with Nullable

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

the class MappingMongoConverter method read.

@Nullable
private <S extends Object> S read(final MongoPersistentEntity<S> entity, final Document bson, final ObjectPath path) {
    DefaultSpELExpressionEvaluator evaluator = new DefaultSpELExpressionEvaluator(bson, spELContext);
    ParameterValueProvider<MongoPersistentProperty> provider = getParameterProvider(entity, bson, evaluator, path);
    EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
    S instance = instantiator.createInstance(entity, provider);
    PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance), conversionService);
    MongoPersistentProperty idProperty = entity.getIdProperty();
    DocumentAccessor documentAccessor = new DocumentAccessor(bson);
    // make sure id property is set before all other properties
    Object idValue = null;
    if (idProperty != null && documentAccessor.hasValue(idProperty)) {
        idValue = readIdValue(path, evaluator, idProperty, documentAccessor);
        accessor.setProperty(idProperty, idValue);
    }
    ObjectPath currentPath = path.push(instance, entity, idValue != null ? bson.get(idProperty.getFieldName()) : null);
    MongoDbPropertyValueProvider valueProvider = new MongoDbPropertyValueProvider(documentAccessor, evaluator, currentPath);
    DbRefResolverCallback callback = new DefaultDbRefResolverCallback(bson, currentPath, evaluator, MappingMongoConverter.this);
    readProperties(entity, accessor, idProperty, documentAccessor, valueProvider, callback);
    return instance;
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) EntityInstantiator(org.springframework.data.convert.EntityInstantiator) DefaultSpELExpressionEvaluator(org.springframework.data.mapping.model.DefaultSpELExpressionEvaluator) ConvertingPropertyAccessor(org.springframework.data.mapping.model.ConvertingPropertyAccessor) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Nullable(org.springframework.lang.Nullable)

Example 4 with Nullable

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

the class MappingMongoConverter method read.

@Nullable
@SuppressWarnings("unchecked")
private <S extends Object> S read(TypeInformation<S> type, @Nullable Bson bson, ObjectPath path) {
    if (null == bson) {
        return null;
    }
    TypeInformation<? extends S> typeToUse = typeMapper.readType(bson, type);
    Class<? extends S> rawType = typeToUse.getType();
    if (conversions.hasCustomReadTarget(bson.getClass(), rawType)) {
        return conversionService.convert(bson, rawType);
    }
    if (DBObject.class.isAssignableFrom(rawType)) {
        return (S) bson;
    }
    if (Document.class.isAssignableFrom(rawType)) {
        return (S) bson;
    }
    if (typeToUse.isCollectionLike() && bson instanceof List) {
        return (S) readCollectionOrArray(typeToUse, (List<?>) bson, path);
    }
    if (typeToUse.isMap()) {
        return (S) readMap(typeToUse, bson, path);
    }
    if (bson instanceof Collection) {
        throw new MappingException(String.format(INCOMPATIBLE_TYPES, bson, BasicDBList.class, typeToUse.getType(), path));
    }
    if (typeToUse.equals(ClassTypeInformation.OBJECT)) {
        return (S) bson;
    }
    // Retrieve persistent entity info
    Document target = bson instanceof BasicDBObject ? new Document((BasicDBObject) bson) : (Document) bson;
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(typeToUse);
    if (entity == null) {
        throw new MappingException(String.format(INVALID_TYPE_TO_READ, target, typeToUse.getType()));
    }
    return read((MongoPersistentEntity<S>) mappingContext.getRequiredPersistentEntity(typeToUse), target, path);
}
Also used : BasicDBList(com.mongodb.BasicDBList) BasicDBObject(com.mongodb.BasicDBObject) Collection(java.util.Collection) BasicDBList(com.mongodb.BasicDBList) List(java.util.List) ArrayList(java.util.ArrayList) Document(org.bson.Document) MappingException(org.springframework.data.mapping.MappingException) Nullable(org.springframework.lang.Nullable)

Example 5 with Nullable

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

the class MappingMongoConverter method convertToMongoType.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.convert.MongoWriter#convertToMongoType(java.lang.Object, org.springframework.data.util.TypeInformation)
	 */
@Nullable
@SuppressWarnings("unchecked")
@Override
public Object convertToMongoType(@Nullable Object obj, TypeInformation<?> typeInformation) {
    if (obj == null) {
        return null;
    }
    Optional<Class<?>> target = conversions.getCustomWriteTarget(obj.getClass());
    if (target.isPresent()) {
        return conversionService.convert(obj, target.get());
    }
    if (conversions.isSimpleType(obj.getClass())) {
        // Doesn't need conversion
        return getPotentiallyConvertedSimpleWrite(obj);
    }
    TypeInformation<?> typeHint = typeInformation;
    if (obj instanceof List) {
        return maybeConvertList((List<Object>) obj, typeHint);
    }
    if (obj instanceof Document) {
        Document newValueDocument = new Document();
        for (String vk : ((Document) obj).keySet()) {
            Object o = ((Document) obj).get(vk);
            newValueDocument.put(vk, convertToMongoType(o, typeHint));
        }
        return newValueDocument;
    }
    if (obj instanceof DBObject) {
        Document newValueDbo = new Document();
        for (String vk : ((DBObject) obj).keySet()) {
            Object o = ((DBObject) obj).get(vk);
            newValueDbo.put(vk, convertToMongoType(o, typeHint));
        }
        return newValueDbo;
    }
    if (obj instanceof Map) {
        Document result = new Document();
        for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) obj).entrySet()) {
            result.put(entry.getKey().toString(), convertToMongoType(entry.getValue(), typeHint));
        }
        return result;
    }
    if (obj.getClass().isArray()) {
        return maybeConvertList(Arrays.asList((Object[]) obj), typeHint);
    }
    if (obj instanceof Collection) {
        return maybeConvertList((Collection<?>) obj, typeHint);
    }
    Document newDocument = new Document();
    this.write(obj, newDocument);
    if (typeInformation == null) {
        return removeTypeInfo(newDocument, true);
    }
    if (typeInformation.getType().equals(NestedDocument.class)) {
        return removeTypeInfo(newDocument, false);
    }
    return !obj.getClass().equals(typeInformation.getType()) ? newDocument : removeTypeInfo(newDocument, true);
}
Also used : Collection(java.util.Collection) BasicDBList(com.mongodb.BasicDBList) List(java.util.List) ArrayList(java.util.ArrayList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Document(org.bson.Document) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) 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