Search code examples
neo4jneo4j-ogm

Map instead of Set for relationship in Neo4j OGM


In the Neo4j OGM tutorial, I see that only Set have been used for mapping relationships. Is it possible to use a map ?

Consider the following example

Suppose I have a class as follows:

 @NodeEntity
    public class Person {
     @Property
       String idCardNumber;

        Map <String, Car> cars;
    }

    @NodeEntity
    public class Car{
      @Id
       String plateNumber;
        @Property
       String color;
    }

How to define a relationship from the class Person and Car given the it's a map that is being used in the class Person ?


Solution

  • As mentioned by @meistermeier, this is not directly possible. But I uses a hack as in my case what i only need is to be able to persist the object directly in the database using Neo4j OGM. In short, i use a set and put the objects in it just before persisting the an instance of class Person. The codes are available below:

    @NodeEntity
        public class Person {
         @Property
           String idCardNumber;
    
            @Transient
            Map <String, Car> cars;
    
            @Relationship(type = "hasCar",direction = Relationship.OUTGOING)
            Set <Car> finalCars;
    
            public void beforeSave(){
                     finalCars = new HashSet<>(cars.values());
             }
        }
    
        @NodeEntity
        public class Car{
          @Id
           String plateNumber;
            @Property
           String color;
        }
    

    Then, just before saving the Person object in the database, the cars are loaded in the set finalCars. This can be done directly in the method responsible for persisting a Person by calling beforeSave() on the insatance.