org.springframework.data.mapping.PersistentPropertyAccessor Java Examples

The following examples show how to use org.springframework.data.mapping.PersistentPropertyAccessor. 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
Source File: OptimisticLockingBeforeBindCallback.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@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 File: TypicalEntityReaderBenchmark.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: MappingVaultConverter.java    From spring-vault with 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 #4
Source File: MappingVaultConverter.java    From spring-vault with 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 #5
Source File: ConverterAwareMappingSpannerEntityWriter.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: SpannerCompositeKeyProperty.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: DatastoreTemplate.java    From spring-cloud-gcp with 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 #8
Source File: ColumnEntityWriter.java    From vertx-spring-boot with 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 #9
Source File: DefaultNeo4jIsNewStrategyTest.java    From sdn-rx with 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 #10
Source File: DefaultNeo4jIsNewStrategyTest.java    From sdn-rx with 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 #11
Source File: Neo4jTemplate.java    From sdn-rx with 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 #12
Source File: DefaultNeo4jConverter.java    From sdn-rx with 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 #13
Source File: DefaultNeo4jConverter.java    From sdn-rx with 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 #14
Source File: NestedRelationshipContext.java    From sdn-rx with 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 #15
Source File: ReactiveNeo4jTemplate.java    From sdn-rx with 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 #16
Source File: MappingAuditableBeanWrapperFactory.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link MappingMetadataAuditableBeanWrapper} for the given target
 * and {@link MappingAuditingMetadata}.
 * @param accessor must not be {@literal null}.
 * @param metadata must not be {@literal null}.
 */
public MappingMetadataAuditableBeanWrapper(PersistentPropertyAccessor<T> accessor,
		MappingAuditingMetadata metadata) {

	Assert.notNull(accessor, "PersistentPropertyAccessor must not be null!");
	Assert.notNull(metadata, "Auditing metadata must not be null!");

	this.accessor = accessor;
	this.metadata = metadata;
}
 
Example #17
Source File: AbstractContentPropertyController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
protected Object getContentProperty(Object domainObj, PersistentProperty<?> property,
		String contentId) {

	PersistentPropertyAccessor accessor = property.getOwner()
			.getPropertyAccessor(domainObj);
	Object contentPropertyObject = accessor.getProperty(property);

	// multi-valued property?
	if (PersistentEntityUtils.isPropertyMultiValued(property)) {
		if (property.isArray()) {
			throw new UnsupportedOperationException();
		}
		else if (property.isCollectionLike()) {
			contentPropertyObject = findContentPropertyObjectInSet(contentId,
					(Collection<?>) contentPropertyObject);
		}
	}

	if (contentPropertyObject == null) {
		throw new ResourceNotFoundException();
	}

	if (BeanUtils.hasFieldWithAnnotation(contentPropertyObject, ContentId.class)) {
		if (BeanUtils.getFieldWithAnnotation(contentPropertyObject,
				ContentId.class) == null) {
			throw new ResourceNotFoundException();
		}
	}

	return contentPropertyObject;
}
 
Example #18
Source File: AbstractContentPropertyController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
protected void setContentProperty(Object domainObj, PersistentProperty<?> property,
		String contentId, Object newValue) {

	PersistentPropertyAccessor accessor = property.getOwner()
			.getPropertyAccessor(domainObj);
	Object contentPropertyObject = accessor.getProperty(property);
	if (contentPropertyObject == null)
		return;
	else if (!PersistentEntityUtils.isPropertyMultiValued(property)) {
		accessor.setProperty(property, newValue);
	}
	else {
		// handle multi-valued
		if (property.isArray()) {
			throw new UnsupportedOperationException();
		}
		else if (property.isCollectionLike()
				&& contentPropertyObject instanceof Set) {
			@SuppressWarnings("unchecked")
			Set<Object> contentSet = (Set<Object>) contentPropertyObject;
			Object oldValue = findContentPropertyObjectInSet(contentId, contentSet);
			contentSet.remove(oldValue);
			if (newValue != null)
				contentSet.add(newValue);
		}
	}
}
 
Example #19
Source File: IdPopulator.java    From sdn-rx with 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 #20
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
protected void writeInternal(Object obj, SecretDocumentAccessor sink, VaultPersistentEntity<?> entity) {

		PersistentPropertyAccessor accessor = entity.getPropertyAccessor(obj);

		VaultPersistentProperty idProperty = entity.getIdProperty();
		if (idProperty != null && !sink.hasValue(idProperty)) {

			Object value = accessor.getProperty(idProperty);

			if (value != null) {
				sink.put(idProperty, value);
			}
		}
		writeProperties(entity, accessor, sink, idProperty);
	}
 
Example #21
Source File: DefaultNeo4jConverter.java    From sdn-rx with 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 #22
Source File: MappingVaultConverter.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private <S> S read(VaultPersistentEntity<S> entity, SecretDocument source) {

		ParameterValueProvider<VaultPersistentProperty> provider = getParameterProvider(entity, source);
		EntityInstantiator instantiator = this.instantiators.getInstantiatorFor(entity);
		S instance = instantiator.createInstance(entity, provider);

		PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(entity.getPropertyAccessor(instance),
				this.conversionService);

		VaultPersistentProperty idProperty = entity.getIdProperty();
		SecretDocumentAccessor documentAccessor = new SecretDocumentAccessor(source);

		// make sure id property is set before all other properties
		Object idValue;

		if (entity.requiresPropertyPopulation()) {
			if (idProperty != null && !entity.isConstructorArgument(idProperty)
					&& documentAccessor.hasValue(idProperty)) {

				idValue = readIdValue(idProperty, documentAccessor);
				accessor.setProperty(idProperty, idValue);
			}

			VaultPropertyValueProvider valueProvider = new VaultPropertyValueProvider(documentAccessor);

			readProperties(entity, accessor, idProperty, documentAccessor, valueProvider);
		}

		return instance;
	}
 
Example #23
Source File: SpannerPersistentEntityImplTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoredProperty() {
	TestEntity t = new TestEntity();
	t.id = "a";
	t.something = "a";
	t.notMapped = "b";
	SpannerPersistentEntity p = new SpannerMappingContext()
			.getPersistentEntity(TestEntity.class);
	PersistentPropertyAccessor accessor = p.getPropertyAccessor(t);
	p.doWithProperties(
			(SimplePropertyHandler) (property) -> assertThat(accessor.getProperty(property)).isNotEqualTo("b"));
}
 
Example #24
Source File: ReactiveOptimisticLockingBeforeBindCallback.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: SpannerRepositoryIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #26
Source File: DefaultNeo4jConverter.java    From sdn-rx with 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 #27
Source File: SpannerMutationFactoryImpl.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #28
Source File: SpannerTemplate.java    From spring-cloud-gcp with 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 #29
Source File: GeneratingIdAccessor.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link GeneratingIdAccessor} using the given {@link PersistentPropertyAccessor}, identifier property
 * and {@link IdentifierGenerator}.
 *
 * @param accessor must not be {@literal null}.
 * @param identifierProperty must not be {@literal null}.
 * @param generator must not be {@literal null}.
 */
GeneratingIdAccessor(PersistentPropertyAccessor<?> accessor, PersistentProperty<?> identifierProperty,
		IdentifierGenerator generator) {

	Assert.notNull(accessor, "PersistentPropertyAccessor must not be null!");
	Assert.notNull(identifierProperty, "Identifier property must not be null!");
	Assert.notNull(generator, "IdentifierGenerator must not be null!");

	this.accessor = accessor;
	this.identifierProperty = identifierProperty;
	this.generator = generator;
}
 
Example #30
Source File: DefaultDatastoreEntityConverter.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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);
				}
			});
}