Search code examples
neo4jspring-data-neo4j-4neo4j-ogm

Node identifiers in Spring data Neo4j


I have a node object that looks like this:

@NodeEntity
public class Title {
    private Long id;
    private String name;
    public void setName(String name){
        this.name=name;
    }
}

The name is the natural identifier for this object. I want to ensure that one Node is created per value for name. What is the recommended way to do this with Spring Data Neo4j? I tried adding this logic to the setter like so:

public void setName(String name){
    this.name=name;
    this.id = new Long(name.hashCode());
}

But when I do this, the nodes are not getting created at all. I'm using Neo4jTemplate to save this object:

Title t = new Title();
t.setName("blah");
neo4jTemplate.save(t);

Solution

  • There is no merge functionality in SDN 4.x. You can do either of the following-

    1. Set up a unique constraint (which you should have anyway), and then deal with a ConstraintViolatedException

    OR

    1. Load the entity by name and use it if it exists, or create a new one if it does not.