Search code examples
javaspring-bootneo4jspring-data-neo4jneo4j-ogm

Saving a subclass or array list in relationship entity on Neo4J Spring Boot OGM


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?


Solution

  • 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<>();