Search code examples
neo4jspring-dataspring-data-neo4jspring-data-graph

converting a NodeProxy to NodeEntity in spring-data-neo4j


I have the below Cypher query. It returns a list of players and list of all the leagues played by each player. Now For each of the returned players, I would like to create the Person NodeEntity instead of using the NodeProxy. Wondering what is the efficient way of doing this.

String q = "START t=node({teamId}) MATCH player-[:PLAYED_WITH_TEAM]->t-[:CONTESTED_IN]->league WITH player AS player, league.startDate AS startDate, league.name AS leagueName ORDER BY startDate RETURN player,  collect(leagueName) AS leagueNames";

Map<String, Object> params = Maps.newHashMap();
params.put("teamId", selectedTeam);

Result<Map<String, Object>> result = template.query(q, params);

final List<Player> players = new ArrayList<Player>();

result.handle(new Handler<Map<String, Object>>()
{
    @Override
    public void handle(Map<String, Object> value)
    {       
        players.add((Player) value.get("player"));
    }
});

Exception

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/avl] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: org.neo4j.kernel.impl.core.NodeProxy cannot be cast to com.aravind.avl.domain.Player] with root cause
java.lang.ClassCastException: org.neo4j.kernel.impl.core.NodeProxy cannot be cast to com.aravind.avl.domain.Player
    at com.aravind.avl.controller.RegistrationController$1.handle(RegistrationController.java:103)

Solution

  • You shoud use the convert method from the Neo4jOperations interface to convert the returned object to its proper class; this is an example:

    neo4jOperations.convert(value.get("player"), Player.class);
    

    The neo4jOperations object is injected by the Spring Data Neo4j infrastructure using the @Autowired annotation.