Search code examples
javaneo4jspring-dataspring-data-neo4j

Neo4J cascade save using Spring Data


I'm using Neo4J with Spring Data, I have multiple Nodes that have inter-relationships, I need to save them for the first time.

Do I need to save each node first and them update the relationship and save again? Or there is a way to tell Neo4J to save them all.

For example:

I have a node called Car that has list of Nodes called Wheels.

@Node
public class Car {

    public String name;

    @Relationship(type="HAS_WHEEL")
    public <List> wheels;

}

@Node 
public class Wheel{

    public String name;

    @Relationship(type="HAS_CAR")
    public Car car;

}

In this case Do I need to save Car and Wheels first, and then update the relation ship with the Car and Wheels returned from the save method?

Or can I just save only Car with the Wheels populated and tell neo4J to cascade the save?


Solution

  • Only saving the Car after you have "attached" the wheel in the Java world, is sufficient.

    Spring Data Neo4j will cascade through all reachable entries when persisting the entity. Theoretically, it would also be possible to save just a Wheel because this cascades also the other way around to the Car and from there to the other three Wheels.

    Two notes on the model above:

    1. Reflect if you really need the bidirectional mapping. SDN will choose a different query style if there can be circles in the graph from the mapping. And this would be the case for bidirectional relationships.
    2. If this is needed, I would use the same relationship type and put something like @Relationship(type="HAS_WHEEL", direction = Direction.INCOMING) on the Car relationship in the Wheel class.