Search in sources :

Example 86 with FieldInfo

use of org.neo4j.ogm.metadata.FieldInfo in project neo4j-ogm by neo4j.

the class MappingContext method generateIdIfNecessary.

private static void generateIdIfNecessary(Object entity, ClassInfo classInfo) {
    if (classInfo.idStrategyClass() == null || InternalIdStrategy.class.equals(classInfo.idStrategyClass())) {
        return;
    }
    if (classInfo.idStrategy() == null) {
        throw new MappingException("Id strategy " + classInfo.idStrategyClass() + " could not be instantiated " + "and wasn't registered. Either provide no argument constructor or register instance " + "with SessionFactory");
    }
    FieldInfo primaryIndexField = classInfo.primaryIndexField();
    Object existingUuid = classInfo.readPrimaryIndexValueOf(entity);
    if (existingUuid == null) {
        IdStrategy strategy = classInfo.idStrategy();
        Object id = strategy.generateId(entity);
        if (strategy instanceof UuidStrategy && primaryIndexField.isTypeOf(String.class)) {
            id = id.toString();
        }
        primaryIndexField.writeDirect(entity, id);
    }
}
Also used : IdStrategy(org.neo4j.ogm.id.IdStrategy) InternalIdStrategy(org.neo4j.ogm.id.InternalIdStrategy) UuidStrategy(org.neo4j.ogm.id.UuidStrategy) InternalIdStrategy(org.neo4j.ogm.id.InternalIdStrategy) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) MappingException(org.neo4j.ogm.exception.core.MappingException)

Example 87 with FieldInfo

use of org.neo4j.ogm.metadata.FieldInfo in project neo4j-ogm by neo4j.

the class MappingContext method neighbours.

/**
 * Get related objects of an entity / relationship. Used in deletion scenarios.
 *
 * @param entity The entity to look neighbours for.
 * @return If entity is a relationship, end and start nodes. If entity is a node, the relations pointing to it.
 */
public Set<Object> neighbours(Object entity) {
    return optionalNativeId(entity).filter(id -> id >= 0).map(id -> {
        Set<Object> neighbours = new HashSet<>();
        Class<?> type = entity.getClass();
        if (!metaData.isRelationshipEntity(type.getName())) {
            if (getNodeEntity(id) != null) {
                // todo: refactor to create a list of mappedRelationships from a nodeEntity id.
                for (MappedRelationship mappedRelationship : relationshipRegister) {
                    if (mappedRelationship.getStartNodeId() == id || mappedRelationship.getEndNodeId() == id) {
                        Object affectedObject = mappedRelationship.getEndNodeId() == id ? getNodeEntity(mappedRelationship.getStartNodeId()) : getNodeEntity(mappedRelationship.getEndNodeId());
                        if (affectedObject != null) {
                            neighbours.add(affectedObject);
                        }
                    }
                }
            }
        } else if (relationshipEntityRegister.containsKey(id)) {
            ClassInfo classInfo = metaData.classInfo(type.getName());
            FieldInfo startNodeReader = classInfo.getStartNodeReader();
            FieldInfo endNodeReader = classInfo.getEndNodeReader();
            neighbours.add(startNodeReader.read(entity));
            neighbours.add(endNodeReader.read(entity));
        }
        return neighbours;
    }).orElseGet(Collections::emptySet);
}
Also used : Iterator(java.util.Iterator) IdStrategy(org.neo4j.ogm.id.IdStrategy) MetaData(org.neo4j.ogm.metadata.MetaData) Collection(java.util.Collection) Set(java.util.Set) InternalIdStrategy(org.neo4j.ogm.id.InternalIdStrategy) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Map(java.util.Map) UuidStrategy(org.neo4j.ogm.id.UuidStrategy) Optional(java.util.Optional) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) Queue(java.util.Queue) MappingException(org.neo4j.ogm.exception.core.MappingException) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) NodeEntity(org.neo4j.ogm.annotation.NodeEntity) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) EntityUtils(org.neo4j.ogm.utils.EntityUtils) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Collections(java.util.Collections) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) ClassInfo(org.neo4j.ogm.metadata.ClassInfo)

Example 88 with FieldInfo

use of org.neo4j.ogm.metadata.FieldInfo in project neo4j-ogm by neo4j.

the class SingleUseEntityMapper method writeProperty.

private void writeProperty(ClassInfo classInfo, Object instance, Map.Entry<String, Object> property) {
    String key = property.getKey();
    FieldInfo writer = classInfo.getFieldInfo(key);
    if (writer == null) {
        // Check relationships
        FieldInfo fieldInfo = classInfo.relationshipFieldByName(key);
        if (fieldInfo != null) {
            writer = fieldInfo;
        }
    }
    boolean isComposite = false;
    if (writer == null) {
        // Check property maps
        Optional<FieldInfo> optionalMatchingComposite = findMatchingCompositeField(classInfo, key);
        if (optionalMatchingComposite.isPresent()) {
            writer = optionalMatchingComposite.get();
            isComposite = true;
        }
    }
    if (writer == null) {
        logger.warn("Unable to find property: {} on class: {} for writing", key, classInfo.name());
    } else {
        // That's what we're gonna write too
        Class<?> effectiveFieldType = writer.type();
        // This takes attribute and composite converters into consideration.
        Class<?> elementType = writer.convertedType();
        if (elementType == null) {
            // If it is not a converted type, we retrieve the element type (not the field type, which maybe a collection)
            elementType = DescriptorMappings.getType(writer.getTypeDescriptor());
        }
        Predicate<Class<?>> isCollectionLike = c -> c != null && (c.isArray() || Iterable.class.isAssignableFrom(c));
        boolean targetIsCollection = isCollectionLike.test(effectiveFieldType);
        Object value = property.getValue();
        // the field as a collection anyway.
        if (!targetIsCollection && GenericUtils.isGenericField(writer.getField()) && value != null && isCollectionLike.test(value.getClass())) {
            targetIsCollection = true;
        }
        if (metadata.classInfo(elementType) != null) {
            value = mapKnownEntityType(elementType, key, value, targetIsCollection);
        } else if (isComposite) {
            value = getAndMergeExistingCompositeValue(instance, key, writer, value);
        }
        // merge iterable / arrays and co-erce to the correct attribute type
        if (targetIsCollection) {
            if (value == null) {
                value = Collections.emptyList();
            } else if (value.getClass().isArray()) {
                value = Arrays.asList((Object[]) value);
            }
            if (effectiveFieldType.isArray()) {
                value = EntityAccessManager.merge(effectiveFieldType, value, new Object[] {}, elementType);
            } else {
                value = EntityAccessManager.merge(effectiveFieldType, value, Collections.emptyList(), elementType);
            }
        }
        writer.write(instance, value);
    }
}
Also used : EntityAccessManager(org.neo4j.ogm.metadata.reflect.EntityAccessManager) EntityInstantiator(org.neo4j.ogm.session.EntityInstantiator) Arrays(java.util.Arrays) CompositeAttributeConverter(org.neo4j.ogm.typeconversion.CompositeAttributeConverter) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Properties(org.neo4j.ogm.annotation.Properties) ArrayList(java.util.ArrayList) ObjectAnnotations(org.neo4j.ogm.metadata.ObjectAnnotations) RowModel(org.neo4j.ogm.model.RowModel) Map(java.util.Map) GenericUtils(org.neo4j.ogm.metadata.reflect.GenericUtils) MapCompositeConverter(org.neo4j.ogm.typeconversion.MapCompositeConverter) EntityFactory(org.neo4j.ogm.metadata.reflect.EntityFactory) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) MetaData(org.neo4j.ogm.metadata.MetaData) Collection(java.util.Collection) List(java.util.List) ClassUtils(org.neo4j.ogm.support.ClassUtils) DescriptorMappings(org.neo4j.ogm.metadata.DescriptorMappings) CollectionUtils(org.neo4j.ogm.support.CollectionUtils) Entry(java.util.Map.Entry) Optional(java.util.Optional) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) Pattern(java.util.regex.Pattern) MappingException(org.neo4j.ogm.exception.core.MappingException) Collections(java.util.Collections) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) FieldInfo(org.neo4j.ogm.metadata.FieldInfo)

Example 89 with FieldInfo

use of org.neo4j.ogm.metadata.FieldInfo in project neo4j-ogm by neo4j.

the class Neo4jSession method queryStatementsFor.

// 
// These helper methods for the delegates are deliberately NOT defined on the Session interface
// 
public <T, ID extends Serializable> QueryStatements<ID> queryStatementsFor(Class<T> type, int depth) {
    final FieldInfo fieldInfo = metaData.classInfo(type.getName()).primaryIndexField();
    String primaryIdName = fieldInfo != null ? fieldInfo.property() : null;
    if (metaData.isRelationshipEntity(type.getName())) {
        return new RelationshipQueryStatements<>(primaryIdName, loadRelationshipClauseBuilder(depth));
    } else {
        return new NodeQueryStatements<>(primaryIdName, loadNodeClauseBuilder(depth));
    }
}
Also used : RelationshipQueryStatements(org.neo4j.ogm.session.request.strategy.impl.RelationshipQueryStatements) NodeQueryStatements(org.neo4j.ogm.session.request.strategy.impl.NodeQueryStatements) FieldInfo(org.neo4j.ogm.metadata.FieldInfo)

Example 90 with FieldInfo

use of org.neo4j.ogm.metadata.FieldInfo in project neo4j-ogm by neo4j.

the class AnnotatedFieldAndNonAnnotatedSetterTest method shouldPreferAnnotatedFieldWithNonAnnotatedSetterForRelationshipEntity.

@Test
public void shouldPreferAnnotatedFieldWithNonAnnotatedSetterForRelationshipEntity() {
    ClassInfo classInfo = this.domainInfo.getClass(End.class.getName());
    RelEntity relEntity = new RelEntity();
    Set<RelEntity> parameter = new HashSet();
    parameter.addAll(Arrays.asList(relEntity));
    FieldInfo objectAccess = EntityAccessManager.getRelationalWriter(classInfo, "REL_ENTITY_TYPE", Relationship.Direction.INCOMING, relEntity);
    assertThat(objectAccess).as("The resultant object accessor shouldn't be null").isNotNull();
    assertThat(objectAccess instanceof FieldInfo).as("The access mechanism should be via the field").isTrue();
    End end = new End();
    objectAccess.write(end, parameter);
    assertThat(parameter).isEqualTo(end.getRelEntities());
}
Also used : FieldInfo(org.neo4j.ogm.metadata.FieldInfo) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

FieldInfo (org.neo4j.ogm.metadata.FieldInfo)142 Test (org.junit.Test)102 ClassInfo (org.neo4j.ogm.metadata.ClassInfo)100 ArrayList (java.util.ArrayList)12 Date (java.util.Date)7 HashSet (java.util.HashSet)6 HashMap (java.util.HashMap)5 Collection (java.util.Collection)4 Satellite (org.neo4j.ogm.domain.satellites.Satellite)4 MappingException (org.neo4j.ogm.exception.core.MappingException)4 CompileContext (org.neo4j.ogm.cypher.compiler.CompileContext)3 Person (org.neo4j.ogm.domain.convertible.enums.Person)3 Member (org.neo4j.ogm.domain.forum.Member)3 Topic (org.neo4j.ogm.domain.forum.Topic)3 Post (org.neo4j.ogm.domain.forum.activity.Post)3 MetaData (org.neo4j.ogm.metadata.MetaData)3 Collections (java.util.Collections)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2