3

I have insert some node into Neo4j DB.And I want to select some node from database and cast it to specific class.

Here are some code about the problem:

class Service {
    Neo4jTemplate neo4jTemplate

    @Transactional
    def find() {
        def id1 = 11
        //Knowledge k = neo4jTemplate.findOne(1, Knowledge)
        Result result = neo4jTemplate.query("start n=node(11) return ID(n),n.name,n.age;", null)
    //how to cast the result to User class
        println "the tpye of result called User is  "+   result.to(User.class).is(cn.edu.bnuz.itc.bok.sub2.User.class)
    }

}

The detail about node like :

+-------------------------------------------------------------------------+
| Node[11]{career:"programmer",name:"kelvin",age:35,introduce:"lazy doy"} |
+-------------------------------------------------------------------------+

        @NodeEntity
        class User {
        @GraphId
        Long id;
        String name;
        int age;
}

I just want get the node's id, name, age from db and put it into a User class. But it failed many time with many method.

Here I have encounter a problem which is :How can I cast the result to my target class? I have try many method to cast but fail finally.Thank you for you attention.

alexbt
  • 16,415
  • 6
  • 78
  • 87

1 Answers1

1

Return the user node from the query and call the to method of the returned Result with the desired class as argument:

Result result = neo4jTemplate.query("start n=node(11) return n", null);
for(User u : result.to(User.class)) {
    doSomethingWith(u);
}

You may want to consider using repositories that support cypher queries like:

public interface UserRepository extends GraphRepository<User> {
    @Query("start n=node(11) return n")
    Iterable<User> getUser11();
}
James
  • 11,654
  • 6
  • 52
  • 81
  • Ok,It works now. Thank you so much. I have tried following method to achieve it. Result result = neo4jTemplate.query("start n=node(11) return ID(n),n.name,n.age;", null) List list = result.collect{new User(it)} Two method can fulfill my requirement. At the end, thanks again. – kelvin7.feng Dec 14 '12 at 14:22
  • 2
    you can also use: `result.to(User.class).as(List.class)` – Michael Hunger Dec 19 '12 at 18:24