Search in sources :

Example 31 with MongoPersistentProperty

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

the class QueryMapper method isAssociationConversionNecessary.

/**
 * Returns whether the given {@link Field} represents an association reference that together with the given value
 * requires conversion to a {@link org.springframework.data.mongodb.core.mapping.DBRef} object. We check whether the
 * type of the given value is compatible with the type of the given document field in order to deal with potential
 * query field exclusions, since MongoDB uses the {@code int} {@literal 0} as an indicator for an excluded field.
 *
 * @param documentField must not be {@literal null}.
 * @param value
 * @return
 */
protected boolean isAssociationConversionNecessary(Field documentField, @Nullable Object value) {
    Assert.notNull(documentField, "Document field must not be null!");
    if (value == null) {
        return false;
    }
    if (!documentField.isAssociation()) {
        return false;
    }
    Class<? extends Object> type = value.getClass();
    MongoPersistentProperty property = documentField.getProperty();
    if (property.getActualType().isAssignableFrom(type)) {
        return true;
    }
    MongoPersistentEntity<?> entity = documentField.getPropertyEntity();
    return entity.hasIdProperty() && (type.equals(DBRef.class) || entity.getRequiredIdProperty().getActualType().isAssignableFrom(type));
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) DBRef(com.mongodb.DBRef)

Example 32 with MongoPersistentProperty

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

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

the class MongoQueryCreator method from.

/**
 * Populates the given {@link CriteriaDefinition} depending on the {@link Part} given.
 *
 * @param part
 * @param property
 * @param criteria
 * @param parameters
 * @return
 */
private Criteria from(Part part, MongoPersistentProperty property, Criteria criteria, Iterator<Object> parameters) {
    Type type = part.getType();
    switch(type) {
        case AFTER:
        case GREATER_THAN:
            return criteria.gt(parameters.next());
        case GREATER_THAN_EQUAL:
            return criteria.gte(parameters.next());
        case BEFORE:
        case LESS_THAN:
            return criteria.lt(parameters.next());
        case LESS_THAN_EQUAL:
            return criteria.lte(parameters.next());
        case BETWEEN:
            return criteria.gt(parameters.next()).lt(parameters.next());
        case IS_NOT_NULL:
            return criteria.ne(null);
        case IS_NULL:
            return criteria.is(null);
        case NOT_IN:
            return criteria.nin(nextAsArray(parameters));
        case IN:
            return criteria.in(nextAsArray(parameters));
        case LIKE:
        case STARTING_WITH:
        case ENDING_WITH:
        case CONTAINING:
            return createContainingCriteria(part, property, criteria, parameters);
        case NOT_LIKE:
            return createContainingCriteria(part, property, criteria.not(), parameters);
        case NOT_CONTAINING:
            return createContainingCriteria(part, property, criteria.not(), parameters);
        case REGEX:
            return criteria.regex(parameters.next().toString());
        case EXISTS:
            return criteria.exists((Boolean) parameters.next());
        case TRUE:
            return criteria.is(true);
        case FALSE:
            return criteria.is(false);
        case NEAR:
            Range<Distance> range = accessor.getDistanceRange();
            Optional<Distance> distance = range.getUpperBound().getValue();
            Optional<Distance> minDistance = range.getLowerBound().getValue();
            Point point = accessor.getGeoNearLocation();
            Point pointToUse = point == null ? nextAs(parameters, Point.class) : point;
            boolean isSpherical = isSpherical(property);
            return distance.map(it -> {
                if (isSpherical || !Metrics.NEUTRAL.equals(it.getMetric())) {
                    criteria.nearSphere(pointToUse);
                } else {
                    criteria.near(pointToUse);
                }
                criteria.maxDistance(it.getNormalizedValue());
                minDistance.ifPresent(min -> criteria.minDistance(min.getNormalizedValue()));
                return criteria;
            }).orElseGet(() -> isSpherical ? criteria.nearSphere(pointToUse) : criteria.near(pointToUse));
        case WITHIN:
            Object parameter = parameters.next();
            return criteria.within((Shape) parameter);
        case SIMPLE_PROPERTY:
            return isSimpleComparisionPossible(part) ? criteria.is(parameters.next()) : createLikeRegexCriteriaOrThrow(part, property, criteria, parameters, false);
        case NEGATING_SIMPLE_PROPERTY:
            return isSimpleComparisionPossible(part) ? criteria.ne(parameters.next()) : createLikeRegexCriteriaOrThrow(part, property, criteria, parameters, true);
        default:
            throw new IllegalArgumentException("Unsupported keyword!");
    }
}
Also used : MongoRegexCreator(org.springframework.data.mongodb.core.query.MongoRegexCreator) Arrays(java.util.Arrays) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) IgnoreCaseType(org.springframework.data.repository.query.parser.Part.IgnoreCaseType) Metrics(org.springframework.data.geo.Metrics) LoggerFactory(org.slf4j.LoggerFactory) Shape(org.springframework.data.geo.Shape) Type(org.springframework.data.repository.query.parser.Part.Type) MappingContext(org.springframework.data.mapping.context.MappingContext) Part(org.springframework.data.repository.query.parser.Part) Distance(org.springframework.data.geo.Distance) AbstractQueryCreator(org.springframework.data.repository.query.parser.AbstractQueryCreator) Sort(org.springframework.data.domain.Sort) MatchMode(org.springframework.data.mongodb.core.query.MongoRegexCreator.MatchMode) Point(org.springframework.data.geo.Point) Logger(org.slf4j.Logger) ClassUtils(org.springframework.util.ClassUtils) Iterator(java.util.Iterator) GeoSpatialIndexType(org.springframework.data.mongodb.core.index.GeoSpatialIndexType) PotentiallyConvertingIterator(org.springframework.data.mongodb.repository.query.ConvertingParameterAccessor.PotentiallyConvertingIterator) PartTree(org.springframework.data.repository.query.parser.PartTree) Collection(java.util.Collection) Range(org.springframework.data.domain.Range) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) PersistentPropertyPath(org.springframework.data.mapping.context.PersistentPropertyPath) CriteriaDefinition(org.springframework.data.mongodb.core.query.CriteriaDefinition) Optional(java.util.Optional) PropertyPath(org.springframework.data.mapping.PropertyPath) GeoSpatialIndexed(org.springframework.data.mongodb.core.index.GeoSpatialIndexed) Assert(org.springframework.util.Assert) IgnoreCaseType(org.springframework.data.repository.query.parser.Part.IgnoreCaseType) Type(org.springframework.data.repository.query.parser.Part.Type) GeoSpatialIndexType(org.springframework.data.mongodb.core.index.GeoSpatialIndexType) Point(org.springframework.data.geo.Point) Distance(org.springframework.data.geo.Distance)

Example 34 with MongoPersistentProperty

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

the class MongoQueryCreator method and.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.query.parser.AbstractQueryCreator#and(org.springframework.data.repository.query.parser.Part, java.lang.Object, java.util.Iterator)
	 */
@Override
protected Criteria and(Part part, Criteria base, Iterator<Object> iterator) {
    if (base == null) {
        return create(part, iterator);
    }
    PersistentPropertyPath<MongoPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty());
    MongoPersistentProperty property = path.getLeafProperty();
    return from(part, property, base.and(path.toDotPath()), (PotentiallyConvertingIterator) iterator);
}
Also used : MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)

Example 35 with MongoPersistentProperty

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

the class SpringDataMongodbSerializer method getPropertyForPotentialDbRef.

/**
 * Checks the given {@literal path} for referencing the {@literal id} property of a {@link DBRef} referenced object.
 * If so it returns the referenced {@link MongoPersistentProperty} of the {@link DBRef} instead of the {@literal id}
 * property.
 *
 * @param path
 * @return
 */
private MongoPersistentProperty getPropertyForPotentialDbRef(Path<?> path) {
    if (path == null) {
        return null;
    }
    MongoPersistentProperty property = getPropertyFor(path);
    PathMetadata metadata = path.getMetadata();
    if (property != null && property.isIdProperty() && metadata != null && metadata.getParent() != null) {
        return getPropertyFor(metadata.getParent());
    }
    return property;
}
Also used : PathMetadata(com.querydsl.core.types.PathMetadata) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)

Aggregations

MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)40 Document (org.bson.Document)13 DBRef (com.mongodb.DBRef)10 Test (org.junit.Test)9 MappingException (org.springframework.data.mapping.MappingException)6 PersistentPropertyAccessor (org.springframework.data.mapping.PersistentPropertyAccessor)6 ConvertingPropertyAccessor (org.springframework.data.mapping.model.ConvertingPropertyAccessor)6 MongoPersistentEntity (org.springframework.data.mongodb.core.mapping.MongoPersistentEntity)6 BasicDBObject (com.mongodb.BasicDBObject)5 DBObject (com.mongodb.DBObject)4 ReturnDocument (com.mongodb.client.model.ReturnDocument)4 FullDocument (com.mongodb.client.model.changestream.FullDocument)4 Arrays (java.util.Arrays)3 Iterator (java.util.Iterator)3 ObjectId (org.bson.types.ObjectId)3 InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 List (java.util.List)2