@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);
虽然给出了Query加载所需的数据,但遗憾的是它无法将其映射到给定的Object(CustomQueryResult
)。但是如果我将它映射到Consumer
,那么它会显示给定的错误:
java.lang.RuntimeException:结果不是预期的大小。预期1 排但发现6
虽然同样的查询工作正常,但如果我使用像
这样的Spring Data Neo4j Repository@Query("MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer) RETURN startNode as node, rel as relationships")
CustomQueryResult findByMobileNumberAndRelationship(String mobileNo);
那么如何直接将给定的查询结果映射到Consumer
或CustomQueryResult
对象?
或者使用具有动态关系名称和深度的Spring Data Neo4j Repository可以做同样的事情:
@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);
虽然我确信上面的代码无效。
答案 0 :(得分:2)
您的查询返回多行
MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, rel as relationships
每个node
重复rel
。存储库基础结构能够处理,但queryForObject
不是 - 它需要单行。
如果您按以下方式修改查询,它应该有效,因此它只返回1行:
MATCH (startNode:Consumer {mobileNumber : {0}})-[rel:HAS_CONTACT *..1]->(endNode:Consumer)
RETURN startNode as node, COLLECT(rel) as relationships