Leward
Leward

Reputation: 125

Is there a way to map an object graph with @Query?

I'm am trying to migrate my SDN3 embedded configuration to using SDN 3.3.0 with a Neo4j instance in server mode (communicating via the REST API then).

When the DB was embedded making a lot of small hits to the DB was not a big deal as Neo4j is capable of handling this kind of queries super fast.

However now that I run my Neo4j separately from my application (ie. in server mode) making a lot of small queries is not advisable because of the network overhead.

User user = userRespository.findOne(123); 
user.fetch(user.getFriends());
user.fetch(user.getManager());
user.fetch(user.getAgency());

This will trigger quite a few queries, especially if I want to get, not a single user, but a list of users.

Can I use the @Query annotation and fetch the user and the related entities and map it into an User object?

I was thinking of something like this:

@Query("MATCH (u:User)-[r:FRIEND]->(f) RETURN u,r,f"

Is such a thing possible with Spring Data Neo4j? Will it be possible with Spring Data Neo4j 4?

Upvotes: 0

Views: 87

Answers (1)

remigio
remigio

Reputation: 4211

You can define a class for query result using the @QueryResult directive and let the method for the query return an object of that class, i.e.:

@QueryResult
public interface UserWithFriends {
    @ResultColumn("u")
    User getUser();

    @ResultColumn("f")
    List<User> friends();
}

@Query("MATCH (u:User)-[:FRIEND]->(f) WHERE u.name={name} RETURN u,f")
UserWithFriends getUserByName(@Param("name") String name);

Upvotes: 1

Related Questions