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

Spring data with neo4j query


See bellow entities.

Person Entity

@NodeEntity
public class Person {  

    @GraphId Long personId; 

    private String name; 

    private String surname;

    @Relationship(type = "ATTENDS", direction = Relationship.OUTGOING) 
    private Set<Event> events;

Attends Entity

@RelationshipEntity(type = "ATTENDS")
public class Attends {

    @GraphId
    private Long id;

    @StartNode
    private Person person;

    @EndNode
    private Event event;

    private Date attendingDate;

Event Entity

@NodeEntity
public class Event {

    @GraphId
    private Long eventId;

    private String eventName;

    @Relationship(type = "ATTENDS", direction = Relationship.INCOMING)
    private Set<Person> persons; 

Here is my API

/persons/{personId}/attends

I want return a list of all the object with a relationship of attending to the person with the id provided, in the example below it would be a list of events.

[{
"attends":{
"attendsId":"1234",
"startDate":"98098098",
"endDate":"098098098",
event:{ "eventId":"1234", "name":"ComicCon" }
},
"attends":{
"attendsId":"1235",
"startDate":"984548098",
"endDate":"45454545",
event:{ "eventId":"1235", "name":"AWS Summit" }

}]

I try this following query but not getting result,

List<Attends> findByPersonPersonId(Long personId);

So How can achieve this result by query ?

Please Guide, Thanks.


Solution

  • Not very sure what exactly you want ? If you want to get all Attends of all Persons or all Attends for a particular person.

    Nevertheless, I have provided answers for both.

    Create a AttendsRepository and add a findByPersonId(String personId) in it.

    public interface AttendsRepository extends GraphRepository<Attends>{
    
        @Query("Match(p:Person {personId:{0}})-[a:ATTENDS]->(e:Event) return a")
        Iterable<Attends> findByPersonId(String personId);
    
    }
    

    Then you can get the desired results by

    @Test
    public void getAllAttends(){
    
        Iterable<Attends> allAttends = attendsRepository.findAll();
        allAttends.forEach(attend -> {
            System.out.println(attend);
        });
    
    }
    
    @Test
    public void getAttendsByPerson(){
    
        String personId = "283f51e9-9ade-4f46-a005-7353b5211c8b";
    
        Iterable<Attends> allAttends = attendsRepository.findByPersonId(personId);
        allAttends.forEach(attend -> {
            System.out.println(attend);
        });
    
    }