Search code examples
javaneo4jspring-dataspring-data-neo4jspring-data-neo4j-4

Add a second label to an inherited node in spring-data-neo4j-4


Let's have this class structure:

@NodeEntity
abstract class BasicNodeEntity {
    @GraphId
    private Long nodeId;
    //...
}

abstract class IdentifiableEntity extends BasicNodeEntity {
    private String id;
    //...
}

abstract class Ad extends IdentifiableEntity {
    //... Ad attibutes
}

class OfferAd extends Ad {
    // ... OfferAd attibutes
}

Saving an OfferAd node through a Neo4jRepository, I expect the node would have two labels: OfferAd and Ad (inherited). However, the label Ad is not added to the node.

I know I can do it saving the node through a cypher query, but I'm wondering if it's posible through a Neo4jRepository instead.

I've reviewed this question (related to SDN3) and I think it's very close to my use case, but it seems to be not working...

Any help would be appreciated. Thanks


Solution

  • The rules for labels are as follows:

    • any plain concrete class in the hierarchy generates a label by default
    • plain abstract class does not generate a label by default
    • plain interface does not generate a label by default
    • any class annotated with @NodeEntity or @NodeEntity(label="something") generates a label
    • empty or null labels must not be allowed
    • classes / hierarchies that are not to be persisted must be annotated with @Transient

    Therefore if you remove abstract from your base class, or add a @NodeEntity annotation, you should see the results you expect.

    Additionally (new in OGM 2.0.4 and fixes in 2.0.5), you can add and remove additional labels by creating a field of type Collection<String> and annotating it with @Labels, for example:

    @Labels
    private List<String> labels = new ArrayList<>();
    

    To use version 2.0.4 (gradle):

    compile "org.neo4j:neo4j-ogm-core:{version}"
    compile "org.neo4j:neo4j-ogm-http-driver:{version}"