Spring data Neo4j can't convert InternalNode back to entity class when retrieving paths

92 views Asked by At

I'm using Neo4jClient to do the following query for retrieving nodes and relationships by paths.

    public Collection<Map<String, Object>> findBookByUniqueIds(List<String> srcUniqueIds, String name) {

        return neo4jClient.query(
                        """
                                MATCH path = (src:Book)-[*1..2]-(target:Book)
                                WHERE src.uniqueId IN $uniqueIds
                                AND toUpper(target.name) = toUpper($name)
                                RETURN nodes(path) AS nodes, relationships(path) AS relations
                                """)
                .bind(srcUniqueIds).to("uniqueIds")
                .bind(name).to("name")
                .fetch().all();
    }

And I extract the data like this:

Collection<Map<String, Object>> result = findBookByUniqueIds(ids, name);
List<Object> nodes = (List<Object>) result.get("nodes");
List<Object> relationships = (List<Object>) result.get("relations");

When I was trying to cask the node back to entity class:

if (nodes.size() == 2) {
    Book book1 = (Book) nodes.get(0);
    Book book2 = (Book) nodes.get(1);
} else if (nodes.size() == 3) {
    Book book1 = (Book) nodes.get(0);
    Author author = (Author) nodes.get(1);
    Book book2 = (Book) nodes.get(2);
}

And I got the exception java.lang.ClassCastException: class org.neo4j.driver.internal.InternalNode cannot be cast to class xxx

Any idea on how to convert the node back to entity class?

Thanks

1

There are 1 answers

1
alexanoid On

I'm not sure if I'm doing it right, but I've encountered this problem myself and haven't found a better solution than simply creating a new object of the class I need and populating it with values that I extract from the InternalNode.

For example:

InternalNode internalNode = (InternalNode) weightedCriteriaArrayElement.get("criterion");

Criterion criterion = new Criterion(); // my entity class
Map<String, Object> nodeProperties = new HashMap<>(internalNode.asMap());
BeanUtils.populate(criterion, nodeProperties);
criterion.setGraphId(internalNode.id());