2
votes

I have a query on how to save a Subclass or ArrayList inside the relationship entity?

My issue: When I pass data to the save call from the repository to save Child as part of the Parent there is no issue or error, but when I retrieve or lookup in the database there is no data present.

Parent Class:

@RelationshipEntity(type = "HAS_DATA")
public class Parent{

private Long id;

private Long sequenceId;

Set<Child> = new HashSet<>();

@StartNode
SomeClass1 someClass1;

@EndNode
SomeClass2 someClass2;

//Getter and Setters
}

Child Class:

public class Child{

Long Id;

String name;

//Getters and Setters
}

How do I achieve this?

2

2 Answers

1
votes

Take a look at the AttributeConverter annotation, however if you need a collection of values on a relationship, consider refactoring your model, to make it a node, with related things.

Example:

Here is an an example attribute converter (in Kotlin) that converts to/from a string array property in Neo4j, to a Java type.

class RoleArrayAttributeConverter : AttributeConverter<Array<Role>, Array<String>>
{

    override fun toEntityAttribute(value: Array<String>): Array<Role>
    {
        return value.map { Role.valueOf(it) }.toTypedArray()
    }

    override fun toGraphProperty(value: Array<Role>): Array<String>
    {
        return value.map { it.toString() }.toTypedArray()
    }

}
1
votes

As per @Jasper Blues suggestion I created my own converter in Java. Answering my own question since I couldn't add this in comments.

public class ChildConverter implements AttributeConverter<Set<Child>, String> {

ObjectMapper mapper = new ObjectMapper();

@Override
public String toGraphProperty(Set<Child> data) {
    String value = "";
    try {
        value = mapper.writeValueAsString(data);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return value;
}

@Override
public Set<Child> toEntityAttribute(String data) {
    Set<Child> mapValue = new HashSet<Child>();
    TypeReference<Set<Child>> typeRef = new TypeReference<Set<Child>>() {
    };
    try {
        mapValue = mapper.readValue(data, typeRef);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mapValue;
}

}

Ensure to add the @Convert annotation in the parent class.

 @Convert(converter = ChildConverter.class)
 Set<Child> = new HashSet<>();