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

The following examples show how to use org.springframework.data.mapping.AssociationHandler. 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
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 2
Source Project: spring-cloud-gcp   Source File: DatastoreTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private <T> void resolveReferenceProperties(DatastorePersistentEntity datastorePersistentEntity,
		BaseEntity entity, T convertedObject, ReadContext context) {
	datastorePersistentEntity.doWithAssociations(
			(AssociationHandler) (association) -> {
				DatastorePersistentProperty referenceProperty = (DatastorePersistentProperty) association
						.getInverse();
				String fieldName = referenceProperty.getFieldName();
				if (entity.contains(fieldName) && !entity.isNull(fieldName)) {
					Class<?> type = referenceProperty.getType();
					Object referenced = computeReferencedField(entity, context, referenceProperty, fieldName, type);
					if (referenced != null) {
						datastorePersistentEntity.getPropertyAccessor(convertedObject)
								.setProperty(referenceProperty, referenced);
					}
				}
			});
}
 
Example 3
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 4
Source Project: sdn-rx   Source File: Neo4jTemplate.java    License: 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 5
Source Project: spring-data-crate   Source File: MappingCrateConverter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Read an incoming {@link CrateDocument} into the target entity.
 *
 * @param entity the target entity.
 * @param source the document to convert.
 * @param parent an optional parent object.
 * @param <R> the entity type.
 * @return the converted entity.
 */
@SuppressWarnings("unchecked")
protected <R> R read(final CratePersistentEntity<R> entity, final CrateDocument source, final Object parent) {
	
	final DefaultSpELExpressionEvaluator evaluator = new DefaultSpELExpressionEvaluator(source, spELContext);
	
    ParameterValueProvider<CratePersistentProperty> provider = getParameterProvider(entity, source, evaluator, parent);
    
    EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);

    R instance = instantiator.createInstance(entity, provider);
    final PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(instance);
    final R result = (R)propertyAccessor.getBean();
    final CratePersistentProperty idProperty = entity.getIdProperty();
    final CratePersistentProperty versionProperty = entity.getVersionProperty();
    
    if(entity.hasIdProperty()) {
    	Object idValue = getValueInternal(idProperty, source, result);
    	propertyAccessor.setProperty(idProperty, idValue);
    }
    
    if(entity.hasVersionProperty()) {
    	Object versionValue = getValueInternal(versionProperty, source, result);
    	propertyAccessor.setProperty(versionProperty, versionValue);
    }
    
    for(CratePersistentProperty property : entity.getPersistentProperties()) {
    	// skip id and version properties as they may have potentially been set above.  
		if((idProperty != null && idProperty.equals(property)) || (versionProperty != null && versionProperty.equals(property))) {
			continue;
		}
		
		if(!source.containsKey(property.getFieldName()) || entity.isConstructorArgument(property)) {
			continue;
		}
		
		propertyAccessor.setProperty(property, getValueInternal(property, source, result));
    }
    
    entity.doWithAssociations(new AssociationHandler<CratePersistentProperty>() {
    	
      @Override
      public void doWithAssociation(final Association<CratePersistentProperty> association) {	    	  
    	  CratePersistentProperty inverseProp = association.getInverse();
    	  Object obj = getValueInternal(inverseProp, source, result);
    	  propertyAccessor.setProperty(inverseProp, obj);
      }	      
    });

    return result;
  }