Search in sources :

Example 1 with PropertyHandler

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

the class MongoExampleMapper method getMappedPropertyPath.

private String getMappedPropertyPath(String path, Class<?> probeType) {
    MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(probeType);
    Iterator<String> parts = Arrays.asList(path.split("\\.")).iterator();
    final Stack<MongoPersistentProperty> stack = new Stack<>();
    List<String> resultParts = new ArrayList<>();
    while (parts.hasNext()) {
        String part = parts.next();
        MongoPersistentProperty prop = entity.getPersistentProperty(part);
        if (prop == null) {
            entity.doWithProperties((PropertyHandler<MongoPersistentProperty>) property -> {
                if (property.getFieldName().equals(part)) {
                    stack.push(property);
                }
            });
            if (stack.isEmpty()) {
                return "";
            }
            prop = stack.pop();
        }
        resultParts.add(prop.getName());
        if (prop.isEntity() && mappingContext.hasPersistentEntityFor(prop.getActualType())) {
            entity = mappingContext.getRequiredPersistentEntity(prop.getActualType());
        } else {
            break;
        }
    }
    return StringUtils.collectionToDelimitedString(resultParts, ".");
}
Also used : Document(org.bson.Document) MongoRegexCreator(org.springframework.data.mongodb.core.query.MongoRegexCreator) Arrays(java.util.Arrays) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) StringMatcher(org.springframework.data.domain.ExampleMatcher.StringMatcher) MappingContext(org.springframework.data.mapping.context.MappingContext) TypeInformation(org.springframework.data.util.TypeInformation) Stack(java.util.Stack) UntypedExampleMatcher(org.springframework.data.mongodb.core.query.UntypedExampleMatcher) ArrayList(java.util.ArrayList) PropertyHandler(org.springframework.data.mapping.PropertyHandler) ExampleMatcherAccessor(org.springframework.data.support.ExampleMatcherAccessor) HashSet(java.util.HashSet) NullHandler(org.springframework.data.domain.ExampleMatcher.NullHandler) Map(java.util.Map) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) MatchMode(org.springframework.data.mongodb.core.query.MongoRegexCreator.MatchMode) ClassUtils(org.springframework.util.ClassUtils) Iterator(java.util.Iterator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) ObjectUtils(org.springframework.util.ObjectUtils) Set(java.util.Set) Example(org.springframework.data.domain.Example) List(java.util.List) PropertyValueTransformer(org.springframework.data.domain.ExampleMatcher.PropertyValueTransformer) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) ArrayList(java.util.ArrayList) Stack(java.util.Stack)

Example 2 with PropertyHandler

use of org.springframework.data.mapping.PropertyHandler in project commons-dao by reportportal.

the class ReportPortalRepositoryImpl method partialUpdate.

@Override
public void partialUpdate(T t) {
    ID id = getEntityInformation().getId(t);
    if (null == id) {
        throw new IllegalArgumentException("ID property should not be null");
    }
    Update update = new Update();
    final MongoPersistentEntity<?> persistentEntity = mongoOperations.getConverter().getMappingContext().getPersistentEntity(getEntityInformation().getJavaType());
    persistentEntity.doWithProperties((PropertyHandler<MongoPersistentProperty>) persistentProperty -> {
        if (!persistentEntity.isIdProperty(persistentProperty)) {
            Object value = Accessible.on(t).field(persistentProperty.getField()).getValue();
            if (null != value) {
                update.set(persistentProperty.getFieldName(), value);
            }
        }
    });
    WriteResult writeResult = mongoOperations.updateFirst(query(where(persistentEntity.getIdProperty().getFieldName()).is(id)), update, getEntityInformation().getCollectionName());
    if (1 != writeResult.getN()) {
        throw new IncorrectResultSizeDataAccessException(1, writeResult.getN());
    }
}
Also used : IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) java.util(java.util) LoadingCache(com.google.common.cache.LoadingCache) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) ErrorType(com.epam.ta.reportportal.ws.model.ErrorType) AggregationOperation(org.springframework.data.mongodb.core.aggregation.AggregationOperation) QueryBuilder(com.epam.ta.reportportal.database.search.QueryBuilder) AggregationUtils.matchOperationFromFilter(com.epam.ta.reportportal.database.dao.aggregation.AggregationUtils.matchOperationFromFilter) Query.query(org.springframework.data.mongodb.core.query.Query.query) PropertyHandler(org.springframework.data.mapping.PropertyHandler) WriteResult(com.mongodb.WriteResult) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Accessible(com.epam.ta.reportportal.commons.accessible.Accessible) DocumentCallbackHandler(org.springframework.data.mongodb.core.DocumentCallbackHandler) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) Update(org.springframework.data.mongodb.core.query.Update) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) Transient(org.springframework.data.annotation.Transient) Nonnull(javax.annotation.Nonnull) DBRef(org.springframework.data.mongodb.core.mapping.DBRef) Criteria.where(org.springframework.data.mongodb.core.query.Criteria.where) SimpleMongoRepository(org.springframework.data.mongodb.repository.support.SimpleMongoRepository) Queryable(com.epam.ta.reportportal.database.search.Queryable) QueryMapper(org.springframework.data.mongodb.core.convert.QueryMapper) ReportPortalException(com.epam.ta.reportportal.exception.ReportPortalException) MongoEntityInformation(org.springframework.data.mongodb.repository.query.MongoEntityInformation) AggregationResults(org.springframework.data.mongodb.core.aggregation.AggregationResults) PageableExecutionUtils(org.springframework.data.repository.support.PageableExecutionUtils) Page(org.springframework.data.domain.Page) Field(java.lang.reflect.Field) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) Query(org.springframework.data.mongodb.core.query.Query) Serializable(java.io.Serializable) CacheLoader(com.google.common.cache.CacheLoader) CriteriaMap(com.epam.ta.reportportal.database.search.CriteriaMap) MongoOperations(org.springframework.data.mongodb.core.MongoOperations) Modifier(java.lang.reflect.Modifier) ObjectId(org.bson.types.ObjectId) CacheBuilder(com.google.common.cache.CacheBuilder) Iterables.toArray(com.google.common.collect.Iterables.toArray) WriteResult(com.mongodb.WriteResult) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Update(org.springframework.data.mongodb.core.query.Update)

Example 3 with PropertyHandler

use of org.springframework.data.mapping.PropertyHandler 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 4 with PropertyHandler

use of org.springframework.data.mapping.PropertyHandler in project spring-data-jdbc by spring-projects.

the class DefaultDataAccessStrategy method getPropertyMap.

private <S> MapSqlParameterSource getPropertyMap(final S instance, JdbcPersistentEntity<S> persistentEntity) {
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    persistentEntity.doWithProperties((PropertyHandler<JdbcPersistentProperty>) property -> {
        if (!property.isEntity()) {
            Object value = persistentEntity.getPropertyAccessor(instance).getProperty(property);
            Object convertedValue = convert(value, property.getColumnType());
            parameters.addValue(property.getColumnName(), convertedValue, JdbcUtil.sqlTypeFor(property.getColumnType()));
        }
    });
    return parameters;
}
Also used : NonTransientDataAccessException(org.springframework.dao.NonTransientDataAccessException) EntityInformation(org.springframework.data.repository.core.EntityInformation) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) JdbcUtil(org.springframework.data.jdbc.support.JdbcUtil) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) KeyHolder(org.springframework.jdbc.support.KeyHolder) Collectors(java.util.stream.Collectors) NamedParameterJdbcOperations(org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations) PropertyHandler(org.springframework.data.mapping.PropertyHandler) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) Map(java.util.Map) BasicJdbcPersistentEntityInformation(org.springframework.data.jdbc.mapping.model.BasicJdbcPersistentEntityInformation) JdbcPersistentEntity(org.springframework.data.jdbc.mapping.model.JdbcPersistentEntity) RowMapper(org.springframework.jdbc.core.RowMapper) Optional(java.util.Optional) StreamSupport(java.util.stream.StreamSupport) JdbcPersistentProperty(org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty) PropertyPath(org.springframework.data.mapping.PropertyPath) JdbcPersistentEntityInformation(org.springframework.data.jdbc.mapping.model.JdbcPersistentEntityInformation) JdbcMappingContext(org.springframework.data.jdbc.mapping.model.JdbcMappingContext) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) Assert(org.springframework.util.Assert) JdbcPersistentProperty(org.springframework.data.jdbc.mapping.model.JdbcPersistentProperty) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource)

Example 5 with PropertyHandler

use of org.springframework.data.mapping.PropertyHandler in project spring-cloud-gcp by spring-cloud.

the class MappingSpannerReadConverter method read.

/**
 * Reads a single POJO from a Spanner row.
 * @param type the type of POJO
 * @param source the Spanner row
 * @param includeColumns the columns to read. If null then all columns will be read.
 * @param <R> the type of the POJO.
 * @return the POJO
 */
public <R> R read(Class<R> type, Struct source, Set<String> includeColumns) {
    boolean readAllColumns = includeColumns == null;
    R object = instantiate(type);
    SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext.getPersistentEntity(type);
    PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(object);
    persistentEntity.doWithProperties((PropertyHandler<SpannerPersistentProperty>) spannerPersistentProperty -> {
        String columnName = spannerPersistentProperty.getColumnName();
        try {
            if ((!readAllColumns && !includeColumns.contains(columnName)) || source.isNull(columnName)) {
                return;
            }
        } catch (IllegalArgumentException e) {
            throw new SpannerDataException("Unable to read column from Spanner results: " + columnName, e);
        }
        Class propType = spannerPersistentProperty.getType();
        boolean valueSet;
        if (ConversionUtils.isIterableNonByteArrayType(propType)) {
            valueSet = attemptReadIterableValue(spannerPersistentProperty, source, columnName, accessor);
        } else {
            Class sourceType = this.spannerColumnTypeToJavaTypeMapping.get(source.getColumnType(columnName));
            if (sourceType != null && canConvert(sourceType, propType)) {
                valueSet = attemptReadSingleItemValue(spannerPersistentProperty, source, sourceType, columnName, accessor);
            } else {
                valueSet = false;
            }
        }
        if (!valueSet) {
            throw new SpannerDataException(String.format("The value in column with name %s" + " could not be converted to the corresponding property in the entity." + " The property's type is %s.", columnName, propType));
        }
    });
    return object;
}
Also used : Date(com.google.cloud.Date) AbstractStructReader(com.google.cloud.spanner.AbstractStructReader) CustomConversions(org.springframework.data.convert.CustomConversions) ImmutableMap(com.google.common.collect.ImmutableMap) BiFunction(java.util.function.BiFunction) SpannerDataException(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException) Set(java.util.Set) Type(com.google.cloud.spanner.Type) Timestamp(com.google.cloud.Timestamp) Constructor(java.lang.reflect.Constructor) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) PropertyHandler(org.springframework.data.mapping.PropertyHandler) EntityReader(org.springframework.data.convert.EntityReader) List(java.util.List) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty) Struct(com.google.cloud.spanner.Struct) Map(java.util.Map) ByteArray(com.google.cloud.ByteArray) SpannerPersistentEntity(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentEntity) SpannerMappingContext(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) SpannerDataException(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty)

Aggregations

PropertyHandler (org.springframework.data.mapping.PropertyHandler)6 Map (java.util.Map)4 Set (java.util.Set)4 List (java.util.List)3 MongoPersistentEntity (org.springframework.data.mongodb.core.mapping.MongoPersistentEntity)3 MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)3 Assert (org.springframework.util.Assert)3 ByteArray (com.google.cloud.ByteArray)2 Date (com.google.cloud.Date)2 Timestamp (com.google.cloud.Timestamp)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 BiFunction (java.util.function.BiFunction)2 Collectors (java.util.stream.Collectors)2 SpannerDataException (org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException)2 SpannerMappingContext (org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext)2 SpannerPersistentEntity (org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentEntity)2 SpannerPersistentProperty (org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty)2 InvalidDataAccessApiUsageException (org.springframework.dao.InvalidDataAccessApiUsageException)2 CustomConversions (org.springframework.data.convert.CustomConversions)2 Sort (org.springframework.data.domain.Sort)2