Neo4j Session.query() - 如何将查询响应映射到自定义 Java 对象

Neo4j Session.query() - How to map query response to Custom Java Object

我有一个节点实体:

@NodeEntity(label = CollectionNames.CONSUMER)
public class Consumer extends AbstractNode{

    //Properties, removed just for simplicity

    @Relationship(type = RelationshipNames.HAS_CONTACT, direction = Relationship.OUTGOING)
    private Set<HasContact> contactList;

//Constructor & Getters, Setters
}

用于存储自定义查询结果:

@QueryResult
public class CustomQueryResult {

    private AbstractNode node;
    private List<? extends AbstractRelationship> relationships;

    public CustomQueryResult(AbstractNode node, List<? extends AbstractRelationship> relationships){
        this.node = node;
        this.relationships = relationships;
    }

//Default Constructor, Getters & Setters
}

存储库实施

String query = String.format(
                "MATCH (startNode:Consumer {mobileNumber : {mob}})-[rel:%s *%d..%d]->(endNode:%s) RETURN startNode as node, rel as relationships",
                relationshipName, 0, depth, endNode);
        Map<String, Object> params = new HashMap<>();
        params.put("mob", mobileNo);
        CustomQueryResult consumer =  session.queryForObject(CustomQueryResult.class, query, params);

虽然给定的查询加载了所需的数据,但不幸的是它无法将其映射到给定的对象(CustomQueryResult)。但是如果我将它映射到 Consumer 那么它会显示给定的错误:

java.lang.RuntimeException: Result not of expected size. Expected 1 row but found 6

虽然同样的查询工作正常,但如果我使用 Spring Data Neo4j Repository like

@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo);

那么如何将给定的查询结果直接映射到 ConsumerCustomQueryResult 对象中呢?

或者是否可以使用具有动态关系名称和深度的 Spring Data Neo4j 存储库来做同样的事情,例如:

@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:{1} *..{2}]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
    CustomQueryResult findByMobileNumberAndRelationship(String mobileNo, String relationshipName, @Depth int depth);

虽然我确定上面的代码没有工作。

您的查询returns 多行

MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) 
RETURN startNode as node, rel as relationships

其中每个 rel 重复 node。存储库基础结构能够处理该问题,但 queryForObject 不能 - 它需要单行。

如果您按以下方式修改查询,它应该可以工作,因此它 returns 只有 1 行:

MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) 
RETURN startNode as node, COLLECT(rel) as relationships