Java Code Examples for org.springframework.data.mapping.PersistentPropertyAccessor

The following examples show how to use org.springframework.data.mapping.PersistentPropertyAccessor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public Object onBeforeBind(Object entity) {
	Neo4jPersistentEntity<?> neo4jPersistentEntity =
		(Neo4jPersistentEntity<?>) neo4jMappingContext.getRequiredNodeDescription(entity.getClass());

	if (neo4jPersistentEntity.hasVersionProperty()) {
		PersistentPropertyAccessor<Object> propertyAccessor = neo4jPersistentEntity.getPropertyAccessor(entity);
		Neo4jPersistentProperty versionProperty = neo4jPersistentEntity.getRequiredVersionProperty();

		if (!Long.class.isAssignableFrom(versionProperty.getType())) {
			return entity;
		}

		Long versionPropertyValue = (Long) propertyAccessor.getProperty(versionProperty);

		long newVersionValue = 0;
		if (versionPropertyValue != null) {
			newVersionValue = versionPropertyValue + 1;
		}

		propertyAccessor.setProperty(versionProperty, newVersionValue);
	}
	return entity;
}
 
Example 2
Source Project: sdn-rx   Source File: DefaultNeo4jConverter.java    License: Apache License 2.0 6 votes vote down vote up
private PropertyHandler<Neo4jPersistentProperty> populateFrom(
	MapAccessor queryResult,
	PersistentPropertyAccessor<?> propertyAccessor,
	Predicate<Neo4jPersistentProperty> isConstructorParameter,
	Collection<String> surplusLabels
) {
	return property -> {
		if (isConstructorParameter.test(property)) {
			return;
		}

		if (property.isDynamicLabels()) {
			propertyAccessor
				.setProperty(property, createDynamicLabelsProperty(property.getTypeInformation(), surplusLabels));
		} else {
			propertyAccessor.setProperty(property,
				readValueForProperty(extractValueOf(property, queryResult), property.getTypeInformation()));
		}
	};
}
 
Example 3
Source Project: sdn-rx   Source File: DefaultNeo4jConverter.java    License: Apache License 2.0 6 votes vote down vote up
private AssociationHandler<Neo4jPersistentProperty> populateFrom(
	MapAccessor queryResult,
	PersistentPropertyAccessor<?> propertyAccessor,
	Predicate<Neo4jPersistentProperty> isConstructorParameter,
	Collection<RelationshipDescription> relationships,
	KnownObjects knownObjects
) {
	return association -> {

		Neo4jPersistentProperty persistentProperty = association.getInverse();
		if (isConstructorParameter.test(persistentProperty)) {
			return;
		}

		createInstanceOfRelationships(persistentProperty, queryResult, knownObjects, relationships)
			.ifPresent(value -> propertyAccessor.setProperty(persistentProperty, value));
	};
}
 
Example 4
Source Project: sdn-rx   Source File: NestedRelationshipContext.java    License: Apache License 2.0 6 votes vote down vote up
static NestedRelationshipContext of(Association<Neo4jPersistentProperty> handler,
	PersistentPropertyAccessor<?> propertyAccessor,
	Neo4jPersistentEntity<?> neo4jPersistentEntity) {

	Neo4jPersistentProperty inverse = handler.getInverse();

	boolean inverseValueIsEmpty = propertyAccessor.getProperty(inverse) == null;
	Object value = propertyAccessor.getProperty(inverse);

	RelationshipDescription relationship = neo4jPersistentEntity
		.getRelationships().stream()
		.filter(r -> r.getFieldName().equals(inverse.getName()))
		.findFirst().get();

	// if we have a relationship with properties, the targetNodeType is the map key
	Class<?> associationTargetType = relationship.hasRelationshipProperties()
		? inverse.getComponentType()
		: inverse.getAssociationTargetType();

	return new NestedRelationshipContext(inverse, value, relationship, associationTargetType,
		inverseValueIsEmpty);
}
 
Example 5
Source Project: sdn-rx   Source File: ReactiveNeo4jTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private <T> Mono<Tuple2<T, DynamicLabels>> determineDynamicLabels(
	T entityToBeSaved, Neo4jPersistentEntity<?> entityMetaData, @Nullable String inDatabase
) {
	return entityMetaData.getDynamicLabelsProperty().map(p -> {

		PersistentPropertyAccessor propertyAccessor = entityMetaData.getPropertyAccessor(entityToBeSaved);
		ReactiveNeo4jClient.RunnableSpecTightToDatabase runnableQuery = neo4jClient
			.query(() -> renderer.render(cypherGenerator.createStatementReturningDynamicLabels(entityMetaData)))
			.in(inDatabase)
			.bind(propertyAccessor.getProperty(entityMetaData.getRequiredIdProperty())).to(NAME_OF_ID)
			.bind(entityMetaData.getStaticLabels()).to(NAME_OF_STATIC_LABELS_PARAM);

		if (entityMetaData.hasVersionProperty()) {
			runnableQuery = runnableQuery
				.bind((Long) propertyAccessor.getProperty(entityMetaData.getRequiredVersionProperty()) - 1)
				.to(NAME_OF_VERSION_PARAM);
		}

		return runnableQuery.fetch().one()
			.map(m -> (Collection<String>) m.get(NAME_OF_LABELS))
			.switchIfEmpty(Mono.just(Collections.emptyList()))
			.zipWith(Mono.just((Collection<String>) propertyAccessor.getProperty(p)))
			.map(t -> Tuples.of(entityToBeSaved, new DynamicLabels(t.getT1(), t.getT2())));
	}).orElse(Mono.just(Tuples.of(entityToBeSaved, DynamicLabels.EMPTY)));
}
 
Example 6
Source Project: sdn-rx   Source File: Neo4jTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private <T> DynamicLabels determineDynamicLabels(
	T entityToBeSaved, Neo4jPersistentEntity<?> entityMetaData, @Nullable String inDatabase
) {
	return entityMetaData.getDynamicLabelsProperty().map(p -> {

		PersistentPropertyAccessor propertyAccessor = entityMetaData.getPropertyAccessor(entityToBeSaved);
		RunnableSpecTightToDatabase runnableQuery = neo4jClient
			.query(() -> renderer.render(cypherGenerator.createStatementReturningDynamicLabels(entityMetaData)))
			.in(inDatabase)
			.bind(propertyAccessor.getProperty(entityMetaData.getRequiredIdProperty())).to(NAME_OF_ID)
			.bind(entityMetaData.getStaticLabels()).to(NAME_OF_STATIC_LABELS_PARAM);

		if (entityMetaData.hasVersionProperty()) {
			runnableQuery = runnableQuery
				.bind((Long) propertyAccessor.getProperty(entityMetaData.getRequiredVersionProperty()) - 1)
				.to(NAME_OF_VERSION_PARAM);
		}

		Optional<Map<String, Object>> optionalResult = runnableQuery.fetch().one();
		return new DynamicLabels(
			optionalResult.map(r -> (Collection<String>) r.get(NAME_OF_LABELS)).orElseGet(Collections::emptyList),
			(Collection<String>) propertyAccessor.getProperty(p)
		);
	}).orElse(DynamicLabels.EMPTY);
}
 
Example 7
Source Project: sdn-rx   Source File: DefaultNeo4jIsNewStrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldDealWithVersion() {
	Object a = new Object();
	Object b = new Object();
	IdDescription idDescription = IdDescription.forAssignedIds("na");

	doReturn(String.class).when(idProperty).getType();
	doReturn(String.class).when(versionProperty).getType();

	doReturn(idDescription).when(entityMetaData).getIdDescription();
	doReturn(idProperty).when(entityMetaData).getRequiredIdProperty();
	doReturn(versionProperty).when(entityMetaData).getVersionProperty();

	PersistentPropertyAccessor aa = mock(PersistentPropertyAccessor.class);
	doReturn(null).when(aa).getProperty(versionProperty);
	doReturn(aa).when(entityMetaData).getPropertyAccessor(a);

	PersistentPropertyAccessor ab = mock(PersistentPropertyAccessor.class);
	doReturn("A version").when(ab).getProperty(versionProperty);
	doReturn(ab).when(entityMetaData).getPropertyAccessor(b);

	IsNewStrategy strategy = DefaultNeo4jIsNewStrategy.basedOn(entityMetaData);

	assertThat(strategy.isNew(a)).isTrue();
	assertThat(strategy.isNew(b)).isFalse();
}
 
Example 8
Source Project: sdn-rx   Source File: DefaultNeo4jIsNewStrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldDealWithPrimitiveVersion() {
	Object a = new Object();
	Object b = new Object();
	IdDescription idDescription = IdDescription.forAssignedIds("na");

	doReturn(String.class).when(idProperty).getType();
	doReturn(int.class).when(versionProperty).getType();

	doReturn(idDescription).when(entityMetaData).getIdDescription();
	doReturn(idProperty).when(entityMetaData).getRequiredIdProperty();
	doReturn(versionProperty).when(entityMetaData).getVersionProperty();

	PersistentPropertyAccessor aa = mock(PersistentPropertyAccessor.class);
	doReturn(0).when(aa).getProperty(versionProperty);
	doReturn(aa).when(entityMetaData).getPropertyAccessor(a);

	PersistentPropertyAccessor ab = mock(PersistentPropertyAccessor.class);
	doReturn(1).when(ab).getProperty(versionProperty);
	doReturn(ab).when(entityMetaData).getPropertyAccessor(b);

	IsNewStrategy strategy = DefaultNeo4jIsNewStrategy.basedOn(entityMetaData);

	assertThat(strategy.isNew(a)).isTrue();
	assertThat(strategy.isNew(b)).isFalse();
}
 
Example 9
Source Project: vertx-spring-boot   Source File: ColumnEntityWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeProperties(List<ColumnValue> sink, RelationalPersistentEntity<?> entity,
    PersistentPropertyAccessor<?> accessor) {

    for (RelationalPersistentProperty property : entity) {
        if (!property.isWritable()) {
            continue;
        }

        // TODO nested entities
        // TODO custom conversions

        Object value = accessor.getProperty(property);

        if (value != null) {
            sink.add(new ColumnValue(property.getColumnName(), value));
        }
    }
}
 
Example 10
Source Project: spring-cloud-gcp   Source File: DatastoreTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private List<Entity> getDescendantEntitiesForSave(Object entity, Key key, Set<Key> persistedEntities) {
	DatastorePersistentEntity datastorePersistentEntity = this.datastoreMappingContext
			.getPersistentEntity(entity.getClass());
	List<Entity> entitiesToSave = new ArrayList<>();
	datastorePersistentEntity.doWithDescendantProperties(
			(PersistentProperty persistentProperty) -> {
				//Convert and write descendants, applying ancestor from parent entry
				PersistentPropertyAccessor accessor = datastorePersistentEntity.getPropertyAccessor(entity);
				Object val = accessor.getProperty(persistentProperty);
				if (val != null) {
					//we can be sure that the property is an array or an iterable,
					//because we check it in isDescendant
					entitiesToSave
							.addAll(getEntitiesForSave((Iterable<?>) ValueUtil.toListIfArray(val), persistedEntities, key));
				}
			});
	return entitiesToSave;
}
 
Example 11
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);
}
 
Example 12
/**
 * 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 columns to write. If null, then all columns are written.
 */
public void write(Object source, MultipleValueBinder sink,
		Set<String> includeColumns) {
	boolean writeAllColumns = includeColumns == null;
	SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext
			.getPersistentEntity(source.getClass());
	PersistentPropertyAccessor accessor = persistentEntity
			.getPropertyAccessor(source);
	persistentEntity.doWithColumnBackedProperties(
			(spannerPersistentProperty) -> {
				if (spannerPersistentProperty.isEmbedded()) {
					Object embeddedObject = accessor
							.getProperty(spannerPersistentProperty);
					if (embeddedObject != null) {
						write(embeddedObject, sink, includeColumns);
					}
				}
				else if (writeAllColumns || includeColumns
						.contains(spannerPersistentProperty.getColumnName())) {
					writeProperty(sink, accessor, spannerPersistentProperty);
				}
			});
}
 
Example 13
Source Project: spring-vault   Source File: MappingVaultConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void readProperties(VaultPersistentEntity<?> entity, PersistentPropertyAccessor accessor,
		@Nullable VaultPersistentProperty idProperty, SecretDocumentAccessor documentAccessor,
		VaultPropertyValueProvider valueProvider) {

	for (VaultPersistentProperty prop : entity) {

		// we skip the id property since it was already set
		if (idProperty != null && idProperty.equals(prop)) {
			continue;
		}

		if (entity.isConstructorArgument(prop) || !documentAccessor.hasValue(prop)) {
			continue;
		}

		accessor.setProperty(prop, valueProvider.getPropertyValue(prop));
	}
}
 
Example 14
Source Project: spring-vault   Source File: MappingVaultConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeProperties(VaultPersistentEntity<?> entity, PersistentPropertyAccessor accessor,
		SecretDocumentAccessor sink, @Nullable VaultPersistentProperty idProperty) {

	// Write the properties
	for (VaultPersistentProperty prop : entity) {

		if (prop.equals(idProperty) || !prop.isWritable()) {
			continue;
		}

		Object value = accessor.getProperty(prop);

		if (value == null) {
			continue;
		}

		if (!this.conversions.isSimpleType(value.getClass())) {
			writePropertyInternal(value, sink, prop);
		}
		else {

			sink.put(prop, getPotentiallyConvertedSimpleWrite(value));
		}
	}
}
 
Example 15
private void readProperties(Map<String, Object> data, MyPersistentEntity<?> persistentEntity,
		PropertyValueProvider<MyPersistentProperty> valueProvider, PersistentPropertyAccessor<?> accessor) {

	for (MyPersistentProperty prop : persistentEntity) {

		if (prop.isAssociation() && !persistentEntity.isConstructorArgument(prop)) {
			continue;
		}

		// We skip the id property since it was already set

		if (persistentEntity.isIdProperty(prop)) {
			continue;
		}

		if (persistentEntity.isConstructorArgument(prop) || !data.containsKey(persistentEntity.getName())) {
			continue;
		}

		accessor.setProperty(prop, valueProvider.getPropertyValue(prop));
	}
}
 
Example 16
@Override
public Publisher<Object> onBeforeBind(Object entity) {

	return Mono.fromSupplier(() -> {
		Neo4jPersistentEntity<?> neo4jPersistentEntity =
			(Neo4jPersistentEntity<?>) neo4jMappingContext.getRequiredNodeDescription(entity.getClass());

		if (neo4jPersistentEntity.hasVersionProperty()) {
			PersistentPropertyAccessor<Object> propertyAccessor = neo4jPersistentEntity.getPropertyAccessor(entity);
			Neo4jPersistentProperty versionProperty = neo4jPersistentEntity.getRequiredVersionProperty();

			if (!Long.class.isAssignableFrom(versionProperty.getType())) {
				return entity;
			}

			Long versionPropertyValue = (Long) propertyAccessor.getProperty(versionProperty);

			long newVersionValue = 0;
			if (versionPropertyValue != null) {
				newVersionValue = versionPropertyValue + 1;
			}

			propertyAccessor.setProperty(versionProperty, newVersionValue);
		}
		return entity;
	});
}
 
Example 17
Source Project: sdn-rx   Source File: IdPopulator.java    License: Apache License 2.0 5 votes vote down vote up
Object populateIfNecessary(Object entity) {

		Assert.notNull(entity, "Entity may not be null!");

		Neo4jPersistentEntity<?> nodeDescription = neo4jMappingContext.getRequiredPersistentEntity(entity.getClass());
		IdDescription idDescription = nodeDescription.getIdDescription();

		// Filter in two steps to avoid unnecessary object creation.
		if (!idDescription.isExternallyGeneratedId()) {
			return entity;
		}

		PersistentPropertyAccessor propertyAccessor = nodeDescription.getPropertyAccessor(entity);
		Neo4jPersistentProperty idProperty = nodeDescription.getRequiredIdProperty();

		// Check existing ID
		if (propertyAccessor.getProperty(idProperty) != null) {
			return entity;
		}

		IdGenerator<?> idGenerator;

		// Get or create the shared generator
		// Ref has precedence over class
		Optional<String> optionalIdGeneratorRef = idDescription.getIdGeneratorRef();
		if (optionalIdGeneratorRef.isPresent()) {

			idGenerator = neo4jMappingContext
				.getIdGenerator(optionalIdGeneratorRef.get()).orElseThrow(() -> new IllegalStateException(
					"Id generator named " + optionalIdGeneratorRef.get() + " not found!"));
		} else {

			// At this point, the class must be present, so we don't check the optional not anymore
			idGenerator = neo4jMappingContext.getOrCreateIdGeneratorOfType(idDescription.getIdGeneratorClass().get());
		}

		propertyAccessor.setProperty(idProperty, idGenerator.generateId(nodeDescription.getPrimaryLabel(), entity));
		return propertyAccessor.getBean();
	}
 
Example 18
Source Project: sdn-rx   Source File: DefaultNeo4jConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(Object source, Map<String, Object> parameters) {
	Map<String, Object> properties = new HashMap<>();

	Neo4jPersistentEntity<?> nodeDescription =
		(Neo4jPersistentEntity<?>) nodeDescriptionStore.getNodeDescription(source.getClass());

	PersistentPropertyAccessor propertyAccessor = nodeDescription.getPropertyAccessor(source);
	nodeDescription.doWithProperties((Neo4jPersistentProperty p) -> {

		// Skip the internal properties, we don't want them to end up stored as properties
		if (p.isInternalIdProperty() || p.isDynamicLabels()) {
			return;
		}

		final Object value = writeValueFromProperty(propertyAccessor.getProperty(p), p.getTypeInformation());
		properties.put(p.getPropertyName(), value);
	});

	parameters.put(NAME_OF_PROPERTIES_PARAM, properties);

	// in case of relationship properties ignore internal id property
	if (nodeDescription.hasIdProperty()) {
		Neo4jPersistentProperty idProperty = nodeDescription.getRequiredIdProperty();
		parameters.put(NAME_OF_ID,
			writeValueFromProperty(propertyAccessor.getProperty(idProperty), idProperty.getTypeInformation()));
	}
	// in case of relationship properties ignore internal id property
	if (nodeDescription.hasVersionProperty()) {
		Long versionProperty = (Long) propertyAccessor.getProperty(nodeDescription.getRequiredVersionProperty());

		// we incremented this upfront the persist operation so the matching version would be one "before"
		parameters.put(NAME_OF_VERSION_PARAM, versionProperty - 1);
	}
}
 
Example 19
Source Project: sdn-rx   Source File: DefaultNeo4jConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param queryResult     The original query result
 * @param nodeDescription The node description of the current entity to be mapped from the result
 * @param knownObjects    The current list of known objects
 * @param <ET>            As in entity type
 * @return
 */
private <ET> ET map(MapAccessor queryResult,
	Neo4jPersistentEntity<ET> nodeDescription,
	KnownObjects knownObjects) {

	List<String> allLabels = getLabels(queryResult);
	NodeDescriptionAndLabels nodeDescriptionAndLabels = nodeDescriptionStore
		.deriveConcreteNodeDescription(nodeDescription, allLabels);
	Neo4jPersistentEntity<ET> concreteNodeDescription = (Neo4jPersistentEntity<ET>) nodeDescriptionAndLabels
		.getNodeDescription();

	Collection<RelationshipDescription> relationships = concreteNodeDescription.getRelationships();

	ET instance = instantiate(concreteNodeDescription, queryResult, knownObjects, relationships,
		nodeDescriptionAndLabels.getDynamicLabels());

	PersistentPropertyAccessor<ET> propertyAccessor = concreteNodeDescription.getPropertyAccessor(instance);

	if (concreteNodeDescription.requiresPropertyPopulation()) {

		// Fill simple properties
		Predicate<Neo4jPersistentProperty> isConstructorParameter = concreteNodeDescription
			.getPersistenceConstructor()::isConstructorParameter;
		PropertyHandler<Neo4jPersistentProperty> handler = populateFrom(
			queryResult, propertyAccessor, isConstructorParameter, nodeDescriptionAndLabels.getDynamicLabels());
		concreteNodeDescription.doWithProperties(handler);

		// Fill associations
		concreteNodeDescription.doWithAssociations(
			populateFrom(queryResult, propertyAccessor, isConstructorParameter, relationships, knownObjects));
	}
	return instance;
}
 
Example 20
Source Project: sdn-rx   Source File: Neo4jTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private <T> T saveImpl(T instance, @Nullable String inDatabase) {

		Neo4jPersistentEntity entityMetaData = neo4jMappingContext.getPersistentEntity(instance.getClass());
		T entityToBeSaved = eventSupport.maybeCallBeforeBind(instance);

		DynamicLabels dynamicLabels = determineDynamicLabels(entityToBeSaved, entityMetaData, inDatabase);

		Optional<Long> optionalInternalId = neo4jClient
			.query(() -> renderer.render(cypherGenerator.prepareSaveOf(entityMetaData, dynamicLabels)))
			.in(inDatabase)
			.bind((T) entityToBeSaved)
			.with(neo4jMappingContext.getRequiredBinderFunctionFor((Class<T>) entityToBeSaved.getClass()))
			.fetchAs(Long.class).one();

		if (entityMetaData.hasVersionProperty() && !optionalInternalId.isPresent()) {
			throw new OptimisticLockingFailureException(OPTIMISTIC_LOCKING_ERROR_MESSAGE);
		}

		PersistentPropertyAccessor<T> propertyAccessor = entityMetaData.getPropertyAccessor(entityToBeSaved);
		if (!entityMetaData.isUsingInternalIds()) {
			processRelations(entityMetaData, entityToBeSaved, inDatabase);
			return entityToBeSaved;
		} else {
			propertyAccessor.setProperty(entityMetaData.getRequiredIdProperty(), optionalInternalId.get());
			processRelations(entityMetaData, entityToBeSaved, inDatabase);

			return propertyAccessor.getBean();
		}
	}
 
Example 21
Source Project: vertx-spring-boot   Source File: ColumnEntityWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void write(Object source, List<ColumnValue> sink) {
    Class<?> userClass = ClassUtils.getUserClass(source);

    // TODO custom conversions

    RelationalPersistentEntity<?> entity = getPersistentEntity(userClass);
    PersistentPropertyAccessor<?> propertyAccessor = entity.getPropertyAccessor(source);

    writeProperties(sink, entity, propertyAccessor);
}
 
Example 22
Source Project: spring-data   Source File: DefaultArangoConverter.java    License: Apache License 2.0 5 votes vote down vote up
private void readProperty(
	final ArangoPersistentEntity<?> entity,
	final String parentId,
	final PersistentPropertyAccessor<?> accessor,
	final VPackSlice source,
	final ArangoPersistentProperty property) {

	final Object propertyValue = readPropertyValue(entity, parentId, source, property);
	if (propertyValue != null || !property.getType().isPrimitive()) {
		accessor.setProperty(property, propertyValue);
	}
}
 
Example 23
Source Project: spring-data   Source File: ArangoTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private void updateDBFields(final Object value, final DocumentEntity documentEntity) {
	final ArangoPersistentEntity<?> entity = converter.getMappingContext().getPersistentEntity(value.getClass());
	final PersistentPropertyAccessor<?> accessor = entity.getPropertyAccessor(value);
	final ArangoPersistentProperty idProperty = entity.getIdProperty();
	if (idProperty != null && !idProperty.isImmutable()) {
		accessor.setProperty(idProperty, documentEntity.getKey());
	}
	entity.getArangoIdProperty().filter(arangoId -> !arangoId.isImmutable())
			.ifPresent(arangoId -> accessor.setProperty(arangoId, documentEntity.getId()));
	entity.getRevProperty().filter(rev -> !rev.isImmutable())
			.ifPresent(rev -> accessor.setProperty(rev, documentEntity.getRev()));
}
 
Example 24
Source Project: dubbox   Source File: MappingSolrConverter.java    License: Apache License 2.0 5 votes vote down vote up
private <S extends Object> S read(final SolrPersistentEntity<S> entity, final Map<String, ?> source,
		Object parent) {
	ParameterValueProvider<SolrPersistentProperty> parameterValueProvider = getParameterValueProvider(entity,
			source, parent);

	EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
	final S instance = instantiator.createInstance(entity, parameterValueProvider);
	final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance),
			getConversionService());

	entity.doWithProperties(new PropertyHandler<SolrPersistentProperty>() {

		@Override
		public void doWithPersistentProperty(SolrPersistentProperty persistentProperty) {
			if (entity.isConstructorArgument(persistentProperty)) {
				return;
			}

			Object o = getValue(persistentProperty, source, instance);
			if (o != null) {
				accessor.setProperty(persistentProperty, o);
			}
		}
	});

	return instance;
}
 
Example 25
Source Project: spring-data-cosmosdb   Source File: MappingCosmosConverter.java    License: MIT License 5 votes vote down vote up
private ConvertingPropertyAccessor getPropertyAccessor(Object entity) {
    final CosmosPersistentEntity<?> entityInformation =
        mappingContext.getPersistentEntity(entity.getClass());

    Assert.notNull(entityInformation, "EntityInformation should not be null.");
    final PersistentPropertyAccessor accessor = entityInformation.getPropertyAccessor(entity);
    return new ConvertingPropertyAccessor(accessor, conversionService);
}
 
Example 26
Source Project: spring-cloud-gcp   Source File: DatastoreTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private List<Entity> getReferenceEntitiesForSave(Object entity, Builder builder, Set<Key> persistedEntities) {
	DatastorePersistentEntity datastorePersistentEntity = this.datastoreMappingContext
			.getPersistentEntity(entity.getClass());
	List<Entity> entitiesToSave = new ArrayList<>();
	datastorePersistentEntity.doWithAssociations((AssociationHandler) (association) -> {
		PersistentProperty persistentProperty = association.getInverse();
		PersistentPropertyAccessor accessor = datastorePersistentEntity.getPropertyAccessor(entity);
		Object val = accessor.getProperty(persistentProperty);
		if (val == null) {
			return;
		}
		Value<?> value;
		if (LazyUtil.isLazyAndNotLoaded(val)) {
			value = LazyUtil.getKeys(val);
		}
		else if (persistentProperty.isCollectionLike()) {
			Iterable<?> iterableVal = (Iterable<?>) ValueUtil.toListIfArray(val);
			entitiesToSave.addAll(getEntitiesForSave(iterableVal, persistedEntities));
			List<KeyValue> keyValues = StreamSupport.stream((iterableVal).spliterator(), false)
					.map((o) -> KeyValue.of(this.getKey(o, false)))
					.collect(Collectors.toList());
			value = ListValue.of(keyValues);

		}
		else {
			entitiesToSave.addAll(getEntitiesForSave(Collections.singletonList(val), persistedEntities));
			Key key = getKey(val, false);
			value = KeyValue.of(key);
		}
		builder.set(((DatastorePersistentProperty) persistentProperty).getFieldName(), value);
	});
	return entitiesToSave;
}
 
Example 27
@Override
@SuppressWarnings("unchecked")
public void write(Object source, BaseEntity.Builder sink) {
	DatastorePersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(source.getClass());

	String discriminationFieldName = persistentEntity.getDiscriminationFieldName();
	List<String> discriminationValues = persistentEntity.getCompatibleDiscriminationValues();
	if (!discriminationValues.isEmpty() || discriminationFieldName != null) {
		sink.set(discriminationFieldName,
				discriminationValues.stream().map(StringValue::of).collect(Collectors.toList()));
	}
	PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(source);
	persistentEntity.doWithColumnBackedProperties(
			(DatastorePersistentProperty persistentProperty) -> {
				// Datastore doesn't store its Key as a regular field.
				if (persistentProperty.isIdProperty()) {
					return;
				}
				try {
					Object val = accessor.getProperty(persistentProperty);
					Value convertedVal = this.conversions.convertOnWrite(val, persistentProperty);

					if (persistentProperty.isUnindexed()) {
						convertedVal = setExcludeFromIndexes(convertedVal);
					}
					sink.set(persistentProperty.getFieldName(), convertedVal);
				}
				catch (DatastoreDataException ex) {
					throw new DatastoreDataException(
							"Unable to write "
									+ persistentEntity.kindName() + "." + persistentProperty.getFieldName(),
							ex);
				}
			});
}
 
Example 28
@Test
public void testIgnoredProperty() {
	TestEntity t = new TestEntity();
	t.id = "a";
	t.something = "a";
	t.notMapped = "b";
	DatastorePersistentEntity p = new DatastoreMappingContext()
			.getPersistentEntity(TestEntity.class);
	PersistentPropertyAccessor accessor = p.getPropertyAccessor(t);

	p.doWithProperties(
			(SimplePropertyHandler) (property) -> assertThat(accessor.getProperty(property)).isNotEqualTo("b"));
}
 
Example 29
Source Project: spring-cloud-gcp   Source File: SpannerTemplate.java    License: Apache License 2.0 5 votes vote down vote up
private void resolveChildEntity(Object entity, Set<String> includeProperties) {
	SpannerPersistentEntity<?> spannerPersistentEntity = this.mappingContext
			.getPersistentEntity(entity.getClass());
	PersistentPropertyAccessor<?> accessor = spannerPersistentEntity
			.getPropertyAccessor(entity);
	spannerPersistentEntity.doWithInterleavedProperties(
			(spannerPersistentProperty) -> {
				if (includeProperties != null && !includeProperties
						.contains(spannerPersistentEntity.getName())) {
					return;
				}
				//an interleaved property can only be List
				List propertyValue = (List) accessor.getProperty(spannerPersistentProperty);
				if (propertyValue != null) {
					resolveChildEntities(propertyValue, null);
					return;
				}
				Class<?> childType = spannerPersistentProperty.getColumnInnerType();

				Supplier<List> getChildrenEntitiesFunc = () -> queryAndResolveChildren(childType,
						SpannerStatementQueryExecutor.getChildrenRowsQuery(
								this.spannerSchemaUtils.getKey(entity),
								spannerPersistentProperty, this.spannerEntityProcessor.getWriteConverter(),
								this.mappingContext),
						null);

				accessor.setProperty(spannerPersistentProperty,
						spannerPersistentProperty.isLazyInterleaved()
								? ConversionUtils.wrapSimpleLazyProxy(getChildrenEntitiesFunc, List.class)
								: getChildrenEntitiesFunc.get());
			});
}
 
Example 30
@Override
public <T> Mutation delete(Class<T> entityClass, Iterable<? extends T> entities) {
	SpannerPersistentEntity<?> persistentEntity = this.spannerMappingContext
			.getPersistentEntity(entityClass);
	KeySet.Builder builder = KeySet.newBuilder();
	for (T entity : entities) {
		PersistentPropertyAccessor accessor = persistentEntity
				.getPropertyAccessor(entity);
		PersistentProperty idProperty = persistentEntity.getIdProperty();
		Key value = (Key) accessor.getProperty(idProperty);

		builder.addKey(value);
	}
	return delete(entityClass, builder.build());
}