Search code examples
neo4jneo4j-ogm

How can I map a query result to domain objects?


I'm developping a program that uses the neo4j-ogm library directly (aka I don't use any Spring component) and my Neo4J DB has this sorts of relations:

PARAMETER<-[:HAS_PARAMETER]-TASK-[:HAS_STEP]->STEP-[:HAS_PARAMETER]->PARAMETER STEP-[:HAS_STEP]->STEP PARAMETER-[:INITIALIZES]->PARAMETER

I coded all my domain classes (PARAMETER, TASK and STEP).

I write a query like (with a session.query method call): MATCH (:TASK)-[r*]->() return r

Can I directly map the result from my query to domain objects?

EDIT: To be sharper, I've got this class Task

@NodeEntity
    class Task {
        @RelationShip(type = "HAS_STEP")
        Set<Step> steps;

        @RelationShip(type = "HAS_PARAMETER")  
        Set<Parameter> parameters;
    }

I wish fill a Task instance (with steps and parameters) and each step be filled too.


Solution

  • You can use session.query() to return a org.neo4j.ogm.model.Result that contains the results. This is supported only in Neo4j OGM 2.0.1.

    Returning a path is not supported, so you must return the nodes and relationships that comprise the path e.g.

    MATCH p=(t:TASK)-[r*]->() return t, nodes(p), rels(p)

    Then, you can access t from the Result and it will be a hydrated Task. Alternatively, you can access the nodes from the Result for all hydrated entities in the path.

    More examples are in the test here: https://github.com/neo4j/neo4j-ogm/blob/2.0/core/src/test/java/org/neo4j/ogm/persistence/session/capability/QueryCapabilityTest.java

    BTW the blog post that Christophe references is still valid for the OGM functionality as well if you need to understand what can be mapped.