Search in sources :

Example 21 with PersistentPropertyAccessor

use of org.springframework.data.mapping.PersistentPropertyAccessor 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)

Example 22 with PersistentPropertyAccessor

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

the class MappingSpannerWriteConverter method write.

/**
 * Writes an object's properties to the sink.
 * @param source the object to write
 * @param sink the sink to which to write
 * @param includeColumns the properties/columns to write. If null, then all columns
 * are written.
 */
public void write(Object source, WriteBuilder sink, Set<String> includeColumns) {
    boolean writeAllColumns = includeColumns == null;
    SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext.getPersistentEntity(source.getClass());
    PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(source);
    persistentEntity.doWithProperties((PropertyHandler<SpannerPersistentProperty>) spannerPersistentProperty -> {
        if (!writeAllColumns && !includeColumns.contains(spannerPersistentProperty.getColumnName())) {
            return;
        }
        writeProperty(sink, accessor, spannerPersistentProperty);
    });
}
Also used : Date(com.google.cloud.Date) 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) WriteBuilder(com.google.cloud.spanner.Mutation.WriteBuilder) Timestamp(com.google.cloud.Timestamp) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) PropertyHandler(org.springframework.data.mapping.PropertyHandler) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty) Map(java.util.Map) ValueBinder(com.google.cloud.spanner.ValueBinder) BiConsumer(java.util.function.BiConsumer) 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) EntityWriter(org.springframework.data.convert.EntityWriter) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) SpannerPersistentProperty(org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerPersistentProperty)

Example 23 with PersistentPropertyAccessor

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

the class SpannerRepositoryIntegrationTests method existsTest.

@Test
public void existsTest() {
    Trade trade = Trade.aTrade();
    this.tradeRepository.save(trade);
    SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext.getPersistentEntity(Trade.class);
    PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(trade);
    PersistentProperty idProperty = persistentEntity.getIdProperty();
    Key key = (Key) accessor.getProperty(idProperty);
    assertThat(this.tradeRepository.existsById(key)).isTrue();
    this.tradeRepository.delete(trade);
    assertThat(this.tradeRepository.existsById(key)).isFalse();
}
Also used : SubTrade(org.springframework.cloud.gcp.data.spanner.test.domain.SubTrade) Trade(org.springframework.cloud.gcp.data.spanner.test.domain.Trade) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) PersistentProperty(org.springframework.data.mapping.PersistentProperty) Key(com.google.cloud.spanner.Key) AbstractSpannerIntegrationTest(org.springframework.cloud.gcp.data.spanner.test.AbstractSpannerIntegrationTest) Test(org.junit.Test)

Example 24 with PersistentPropertyAccessor

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

the class SpannerCompositeKeyProperty method getId.

Key getId(Object entity) {
    PersistentPropertyAccessor accessor = getOwner().getPropertyAccessor(entity);
    List keyParts = new ArrayList();
    for (SpannerPersistentProperty spannerPersistentProperty : this.primaryKeyColumns) {
        Object value = accessor.getProperty(spannerPersistentProperty);
        if (spannerPersistentProperty.isEmbedded()) {
            Key embeddedKeyParts = this.spannerPersistentEntity.getSpannerMappingContext().getPersistentEntity(spannerPersistentProperty.getType()).getIdProperty().getId(value);
            for (Object keyPart : embeddedKeyParts.getParts()) {
                keyParts.add(keyPart);
            }
        } else if (spannerPersistentProperty.getAnnotatedColumnItemType() == null || value == null) {
            keyParts.add(value);
        } else {
            keyParts.add(this.spannerPersistentEntity.getSpannerEntityProcessor().getSpannerWriteConverter().convert(value, SpannerTypeMapper.getSimpleJavaClassFor(spannerPersistentProperty.getAnnotatedColumnItemType())));
        }
    }
    return this.spannerPersistentEntity.getSpannerEntityProcessor().convertToKey(keyParts);
}
Also used : PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Key(com.google.cloud.spanner.Key)

Example 25 with PersistentPropertyAccessor

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

the class DatastoreTemplate method exampleToQuery.

private <T> StructuredQuery exampleToQuery(Example<T> example, DatastoreQueryOptions queryOptions, boolean keyQuery) {
    validateExample(example);
    T probe = example.getProbe();
    FullEntity.Builder<IncompleteKey> probeEntityBuilder = Entity.newBuilder();
    this.datastoreEntityConverter.write(probe, probeEntityBuilder);
    FullEntity<IncompleteKey> probeEntity = probeEntityBuilder.build();
    DatastorePersistentEntity<?> persistentEntity = this.datastoreMappingContext.getPersistentEntity(example.getProbeType());
    LinkedList<StructuredQuery.Filter> filters = new LinkedList<>();
    NullHandler nullHandler = example.getMatcher().getNullHandler();
    persistentEntity.doWithColumnBackedProperties((persistentProperty) -> {
        if (!ignoredProperty(example, persistentProperty)) {
            Value<?> value = getValue(example, probeEntity, persistentEntity, persistentProperty);
            addFilter(nullHandler, filters, persistentProperty.getFieldName(), value);
        }
    });
    persistentEntity.doWithAssociations((AssociationHandler<DatastorePersistentProperty>) association -> {
        PersistentPropertyAccessor<?> accessor = persistentEntity.getPropertyAccessor(example.getProbe());
        DatastorePersistentProperty property = association.getInverse();
        Object value = accessor.getProperty(property);
        Value<?> key = value == null ? NullValue.of() : KeyValue.of(objectToKeyFactory.getKeyFromObject(value, this.datastoreMappingContext.getPersistentEntity(value.getClass())));
        addFilter(nullHandler, filters, property.getFieldName(), key);
    });
    StructuredQuery.Builder<?> builder = keyQuery ? Query.newKeyQueryBuilder() : Query.newEntityQueryBuilder();
    builder.setKind(persistentEntity.kindName());
    if (!filters.isEmpty()) {
        builder.setFilter(StructuredQuery.CompositeFilter.and(filters.pop(), filters.toArray(new StructuredQuery.Filter[0])));
    }
    applyQueryOptions(builder, queryOptions, persistentEntity);
    return builder.build();
}
Also used : FullEntity(com.google.cloud.datastore.FullEntity) Query(com.google.cloud.datastore.Query) Builder(com.google.cloud.datastore.Entity.Builder) PathElement(com.google.cloud.datastore.PathElement) SliceUtil(org.springframework.cloud.gcp.data.datastore.core.util.SliceUtil) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) Filter(com.google.cloud.datastore.StructuredQuery.Filter) AfterQueryEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterQueryEvent) KeyQuery(com.google.cloud.datastore.KeyQuery) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) QueryResults(com.google.cloud.datastore.QueryResults) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) PersistentProperty(org.springframework.data.mapping.PersistentProperty) AfterFindByKeyEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterFindByKeyEvent) BaseEntity(com.google.cloud.datastore.BaseEntity) DatastoreDataException(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreDataException) Collection(java.util.Collection) KeyValue(com.google.cloud.datastore.KeyValue) AfterSaveEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterSaveEvent) Set(java.util.Set) DatastorePersistentEntity(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentEntity) Example(org.springframework.data.domain.Example) Collectors(java.util.stream.Collectors) IncompleteKey(com.google.cloud.datastore.IncompleteKey) Slice(org.springframework.data.domain.Slice) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) KeyUtil(org.springframework.cloud.gcp.data.datastore.core.util.KeyUtil) ListValue(com.google.cloud.datastore.ListValue) DatastoreMappingContext(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext) BeforeDeleteEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.BeforeDeleteEvent) Key(com.google.cloud.datastore.Key) BeforeSaveEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.BeforeSaveEvent) DatastoreEntityConverter(org.springframework.cloud.gcp.data.datastore.core.convert.DatastoreEntityConverter) SliceImpl(org.springframework.data.domain.SliceImpl) HashMap(java.util.HashMap) Datastore(com.google.cloud.datastore.Datastore) ProjectionEntityQuery(com.google.cloud.datastore.ProjectionEntityQuery) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Cursor(com.google.cloud.datastore.Cursor) HashSet(java.util.HashSet) NullHandler(org.springframework.data.domain.ExampleMatcher.NullHandler) ValueUtil(org.springframework.cloud.gcp.data.datastore.core.util.ValueUtil) Entity(com.google.cloud.datastore.Entity) PropertyFilter(com.google.cloud.datastore.StructuredQuery.PropertyFilter) NullValue(com.google.cloud.datastore.NullValue) StreamSupport(java.util.stream.StreamSupport) Nullable(org.springframework.lang.Nullable) LinkedList(java.util.LinkedList) StructuredQuery(com.google.cloud.datastore.StructuredQuery) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Iterator(java.util.Iterator) TypeUtils(org.springframework.util.TypeUtils) ObjectToKeyFactory(org.springframework.cloud.gcp.data.datastore.core.convert.ObjectToKeyFactory) ExampleMatcher(org.springframework.data.domain.ExampleMatcher) DatastoreReaderWriter(com.google.cloud.datastore.DatastoreReaderWriter) EntityQuery(com.google.cloud.datastore.EntityQuery) AfterDeleteEvent(org.springframework.cloud.gcp.data.datastore.core.mapping.event.AfterDeleteEvent) ApplicationEvent(org.springframework.context.ApplicationEvent) AssociationHandler(org.springframework.data.mapping.AssociationHandler) BaseKey(com.google.cloud.datastore.BaseKey) Value(com.google.cloud.datastore.Value) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty) Collections(java.util.Collections) DatastorePageable(org.springframework.cloud.gcp.data.datastore.repository.query.DatastorePageable) Assert(org.springframework.util.Assert) StructuredQuery(com.google.cloud.datastore.StructuredQuery) NullHandler(org.springframework.data.domain.ExampleMatcher.NullHandler) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) FullEntity(com.google.cloud.datastore.FullEntity) LinkedList(java.util.LinkedList) IncompleteKey(com.google.cloud.datastore.IncompleteKey) Filter(com.google.cloud.datastore.StructuredQuery.Filter) PropertyFilter(com.google.cloud.datastore.StructuredQuery.PropertyFilter) KeyValue(com.google.cloud.datastore.KeyValue) ListValue(com.google.cloud.datastore.ListValue) NullValue(com.google.cloud.datastore.NullValue) Value(com.google.cloud.datastore.Value) DatastorePersistentProperty(org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty)

Aggregations

PersistentPropertyAccessor (org.springframework.data.mapping.PersistentPropertyAccessor)29 Test (org.junit.Test)8 PersistentProperty (org.springframework.data.mapping.PersistentProperty)7 List (java.util.List)6 Key (com.google.cloud.spanner.Key)5 ArrayList (java.util.ArrayList)5 Set (java.util.Set)5 DatastorePersistentProperty (org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentProperty)5 Map (java.util.Map)4 BaseEntity (com.google.cloud.datastore.BaseEntity)3 Entity (com.google.cloud.datastore.Entity)3 FullEntity (com.google.cloud.datastore.FullEntity)3 ListValue (com.google.cloud.datastore.ListValue)3 Value (com.google.cloud.datastore.Value)3 DatastorePersistentEntity (org.springframework.cloud.gcp.data.datastore.core.mapping.DatastorePersistentEntity)3 EntityInstantiator (org.springframework.data.convert.EntityInstantiator)3 PropertyHandler (org.springframework.data.mapping.PropertyHandler)3 MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)3 ClassTypeInformation (org.springframework.data.util.ClassTypeInformation)3 ByteArray (com.google.cloud.ByteArray)2