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

Multiple/Optional EndNode Neo4j


Current scenario:

User is able to have a Car and a Motorcycle, so a user could have 1 relation [:OWNS] :Car and another to :Motorcycle. It is also possible for the user to have neither or just one of them.

U->C & U->M
U->C 
U

Current relationship entity:

@RelationshipEntity(type = "OWNS")                      
public class Owns {

@GraphId                                    
Long relationshipId;                            

private int price;

@StartNode                          
Car car;                                

@EndNode                                    
Motorcycle motor;
}

How do I set a user to have just one of them? because I get error that an EndNode cannot be null, which understandable at this point. is there a way to make another endNode optional?

Thanks


Solution

  • Perhaps a misunderstanding of the @RelationshipEntity? A relationship entity is simply a relationship with properties between two nodes.

    @StartNode                          
    Car car;                                
    
    @EndNode                                    
    Motorcycle motor;
    

    is saying a Car OWNS a Motorcycle.

    What you want instead is a User that owns either a Car or Motorcyle, so if you have a superclass Vehicle as suggested by Michael, then you would have the following:

    @RelationshipEntity(type = "OWNS")                      
    public class Owns {
    
    @GraphId                                    
    Long relationshipId;                            
    
    private int price;
    
    @StartNode                          
    User user;                                
    
    @EndNode                                    
    Vehicle vehicle;
    }
    

    User would have:

    @Relationship(type="OWNS")
    Set<Owns> vehiclesOwned;
    

    and this set can have zero or one or many vehicles in it.