Java Code Examples for org.springframework.data.mapping.PersistentPropertyAccessor#getProperty()

The following examples show how to use org.springframework.data.mapping.PersistentPropertyAccessor#getProperty() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: Neo4jTemplate.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
private void processNestedRelations(Neo4jPersistentEntity<?> neo4jPersistentEntity, Object parentObject,
	@Nullable String inDatabase, NestedRelationshipProcessingStateMachine stateMachine) {

	PersistentPropertyAccessor<?> propertyAccessor = neo4jPersistentEntity.getPropertyAccessor(parentObject);
	Object fromId = propertyAccessor.getProperty(neo4jPersistentEntity.getRequiredIdProperty());

	neo4jPersistentEntity.doWithAssociations((AssociationHandler<Neo4jPersistentProperty>) association -> {

		// create context to bundle parameters
		NestedRelationshipContext relationshipContext = NestedRelationshipContext
			.of(association, propertyAccessor, neo4jPersistentEntity);

		Collection<?> relatedValuesToStore = Relationships
			.unifyRelationshipValue(relationshipContext.getInverse(), relationshipContext.getValue());

		RelationshipDescription relationshipDescription = relationshipContext.getRelationship();
		RelationshipDescription relationshipDescriptionObverse = relationshipDescription.getRelationshipObverse();

		// break recursive procession and deletion of previously created relationships
		ProcessState processState = stateMachine
			.getStateOf(relationshipDescriptionObverse, relatedValuesToStore);
		if (processState == ProcessState.PROCESSED_BOTH) {
			return;
		}

		// remove all relationships before creating all new if the entity is not new
		// this avoids the usage of cache but might have significant impact on overall performance
		if (!neo4jPersistentEntity.isNew(parentObject)) {
			Neo4jPersistentEntity<?> previouslyRelatedPersistentEntity = neo4jMappingContext
				.getPersistentEntity(relationshipContext.getAssociationTargetType());

			Statement relationshipRemoveQuery = cypherGenerator.createRelationshipRemoveQuery(neo4jPersistentEntity,
				relationshipDescription, previouslyRelatedPersistentEntity);

			neo4jClient.query(renderer.render(relationshipRemoveQuery))
				.in(inDatabase)
				.bind(convertIdValues(fromId)).to(FROM_ID_PARAMETER_NAME).run();
		}

		// nothing to do because there is nothing to map
		if (relationshipContext.inverseValueIsEmpty()) {
			return;
		}

		stateMachine.markAsProcessed(relationshipDescription, relatedValuesToStore);

		for (Object relatedValueToStore : relatedValuesToStore) {

			// here map entry is not always anymore a dynamic association
			Object valueToBeSavedPreEvt = relationshipContext
				.identifyAndExtractRelationshipValue(relatedValueToStore);
			valueToBeSavedPreEvt = eventSupport.maybeCallBeforeBind(valueToBeSavedPreEvt);

			Neo4jPersistentEntity<?> targetNodeDescription = neo4jMappingContext
				.getPersistentEntity(valueToBeSavedPreEvt.getClass());

			Long relatedInternalId = saveRelatedNode(valueToBeSavedPreEvt,
				relationshipContext.getAssociationTargetType(),
				targetNodeDescription, inDatabase);

			RelationshipStatementHolder statementHolder = RelationshipStatementHolder.createStatement(
				neo4jMappingContext, neo4jPersistentEntity, relationshipContext, relatedInternalId,
				relatedValueToStore);

			neo4jClient.query(renderer.render(statementHolder.getRelationshipCreationQuery()))
				.in(inDatabase)
				.bind(convertIdValues(fromId)).to(FROM_ID_PARAMETER_NAME)
				.bindAll(statementHolder.getProperties())
				.run();

			// if an internal id is used this must get set to link this entity in the next iteration
			if (targetNodeDescription.isUsingInternalIds()) {
				PersistentPropertyAccessor<?> targetPropertyAccessor = targetNodeDescription
					.getPropertyAccessor(valueToBeSavedPreEvt);
				targetPropertyAccessor
					.setProperty(targetNodeDescription.getRequiredIdProperty(), relatedInternalId);
			}
			if (processState != ProcessState.PROCESSED_ALL_VALUES) {
				processNestedRelations(targetNodeDescription, valueToBeSavedPreEvt, inDatabase, stateMachine);
			}
		}
	});
}
 
Example 14
Source File: ConverterAwareMappingSpannerEntityWriter.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * For each property this method "set"s the column name and finds the corresponding "to"
 * method on the {@link ValueBinder} interface.
 * </p>
 * <pre>
 * {
 * 	&#64;code
 *
 * 	long singerId = my_singer_id;
 * 	Mutation.WriteBuilder writeBuilder = Mutation.newInsertBuilder("Singer")
 * 			.set("SingerId")
 * 			.to(singerId)
 * 			.set("FirstName")
 * 			.to("Billy")
 * 			.set("LastName")
 * 			.to("Joel");
 * }
 * </pre>
 *
 * @param accessor the accessor used to get the value to write
 * @param property the property that will be written
 * @param sink the object that will accept the value to be written
 */
// @formatter:on
@SuppressWarnings("unchecked")
private void writeProperty(MultipleValueBinder sink,
		PersistentPropertyAccessor accessor,
		SpannerPersistentProperty property) {
	Object propertyValue = accessor.getProperty(property);

	Class<?> propertyType = property.getType();
	ValueBinder<WriteBuilder> valueBinder = sink.set(property.getColumnName());

	boolean valueSet = false;

	/*
	 * Due to type erasure, binder methods for Iterable properties must be manually specified.
	 * ByteArray must be excluded since it implements Iterable, but is also explicitly
	 * supported by spanner.
	 */
	if (ConversionUtils.isIterableNonByteArrayType(propertyType)) {
		valueSet = attemptSetIterableValue((Iterable<Object>) propertyValue, valueBinder,
				property, this.writeConverter);
	}
	else {

		// if the property is a commit timestamp, then its Spanner column type is always TIMESTAMP
		// and only the dummy value needs to be written to trigger auto-population of the commit
		// time
		if (property.isCommitTimestamp()) {
			valueSet = attemptSetSingleItemValue(Value.COMMIT_TIMESTAMP, Timestamp.class, valueBinder,
					Timestamp.class, this.writeConverter);
		}
		// use the user's annotated column type if possible
		else if (property.getAnnotatedColumnItemType() != null) {
			valueSet = attemptSetSingleItemValue(propertyValue, propertyType,
					valueBinder,
					SpannerTypeMapper.getSimpleJavaClassFor(property.getAnnotatedColumnItemType()),
					this.writeConverter);
		}
		else {
			if (!valueSet) {
				valueSet = attemptBindSingleValue(propertyValue, propertyType, valueBinder, this.writeConverter);
			}
		}
	}

	if (!valueSet) {
		throw new SpannerDataException(String.format(
				"Unsupported mapping for type: %s", propertyValue.getClass()));
	}
}