Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a List<CustomObject> as a property of a node?

I am trying to persist a list of objects of a class suppose xyz. when I do this in the NodeEntity Class:

@Property
List<xyz> listOfConditions

The Node table when loaded from the neo4j-database via the Neo4jOperations.load(entity) method, will return an error saying :- ERROR mapping GraphModel to NodeEntity type class.

Is there any way to persist a List of Objects onto a nodes properties in Neo4j?. I am using neo4j-ogm-embedded driver and Spring-data-neo4j.

like image 943
KrishnaKant Agrawal Avatar asked Sep 05 '16 06:09

KrishnaKant Agrawal


2 Answers

Neo4j does not support storing another object as a nested property. Neo4j-OGM only supports

any primitive, boxed primitive or String or arrays thereof, essentially anything that naturally fits into a Neo4j node property.

If you want to work around that, you may need to create a custom type convertor. For example,

import org.neo4j.ogm.typeconversion.AttributeConverter

class XYZ{
    XYZ(Integer x, String y) {
        this.x = x
        this.y = y
    }
    Integer x
    String y
}

public class XYZConverter implements AttributeConverter<XYZ, String> {

    @Override
    public String toGraphProperty(XYZ value) {
        return value.x.toString() + "!@#" + value.y
    }

    @Override
    public XYZ toEntityAttribute(String value) {
        String[] split = value.split("!@#")
        return new XYZ(Integer.valueOf(split[0]), split[1])
    }
}

You can then annotate the @NodeEntity with a @Convert like this

@NodeEntity
class Node {
    @GraphId
    Long id;

    @Property
    String name

    @Convert(value = XYZConverter.class)
    XYZ xyz
}

On the flip side, its not a good practice to do this, since ideally you should link Node and XYZ with a 'hasA' relationship. Neo4j has been designed to optimally handle such kind of relationships, so it would be best to play with to strengths of neo4j

like image 193
Abbas Gadhia Avatar answered Nov 06 '22 18:11

Abbas Gadhia


No, nested objects represented as properties on a single node are not supported by the OGM. The only option is to write a custom converter to serialize the nested object to a String representation and store it as a single property.

Otherwise, a list of objects on a node is treated as relationships from the node to those objects.

Here's a link to the manual for further reference: http://neo4j.com/docs/ogm-manual/current/

like image 36
Luanne Avatar answered Nov 06 '22 19:11

Luanne