我使用spring数据neo4j自定义查询,并将其公开给一个宁静的api,但是我没有编写QueryResult
,而是编写了相应的NodeEntity
和RelationshipEntity
bean,但仅节点可以
映射到NodeEntity
,关系不能映射到RelationshipEntity
我已经编写了NodeEntity和RelationshipEntity bean,一个存储库和一个自定义查询,并在neo4j中创建了两个节点和一个关系,以及一个用于显示json的rest控制器
首先,我在neo4j中创建数据:
CREATE (n:Person2 { name: 'tom'})
CREATE (n:Person2 { name: 'jim'})
MATCH (a:Person2),(b:Person2)
WHERE a.name = 'tom' AND b.name = 'jim'
CREATE (a)-[r:Relation2 { name: 'onelink' }]->(b)
RETURN type(r), r.name
然后使用spring数据编写代码:
@NodeEntity(label = "Person")
@Data
public class Person2 {
@Id
@GeneratedValue
private Long id;
private String name;
private String personProp = "someone";
}
@RelationshipEntity(type = "Relation2")
@Data
public class Relation2 {
@Id
@GeneratedValue
private Long id;
private String r2prop="yeyeye";
private String name;
}
存储库
public interface NeiborRepository extends Neo4jRepository {
@Query("MATCH (n {name:'tom'})-[r]->(m {name:'jim'}) return n,r,m")
Iterable<Map<String,Object>> neibor(String identifier);
}
控制器
@RestController
@RequestMapping(path = "/api")
public class Neo4jApi {
private NeiborRepository neibor;
@Autowired
public Neo4jApi(NeiborRepository neibor) {
super();
this.neibor = neibor;
}
@GetMapping(path = "neibor")
public Iterable<Map<String, Object>> neibor(String identifier) {
Iterable<Map<String, Object>> coms = neibor.neibor(identifier);
return coms;
}
}
然后,我访问http://127.0.0.1:8080/api/neibor 结果是:
[{
"n": {
"id": 7206,
"name": "tom",
"personProp": "someone"
},
"r": {
"id": 26,
"version": null,
"type": "Relation2",
"startNode": 7206,
"endNode": 21,
"primaryIdName": null,
"propertyList": [{
"key": "name",
"value": "onelink"
}]
},
"m": {
"id": 21,
"name": "jim",
"personProp": "someone"
}
}]
注意r.propertyList,对于person节点,所有属性都来自Person2 bean,甚至显示了“ personProp”,但是对于关系,它似乎与Relation2 bean不匹配。
所以我尝试将Person2的类名称更改为Person3,json结果变为:
[{
"n": {
"id": 7206,
"version": null,
"labels": ["Person2"],
"removedLabels": null,
"primaryIndex": null,
"propertyList": [{
"key": "name",
"value": "tom"
}]
},
"r": {
"id": 26,
"version": null,
"type": "Relation2",
"startNode": 7206,
"endNode": 21,
"primaryIdName": null,
"propertyList": [{
"key": "name",
"value": "onelink"
}]
},
"m": {
"id": 21,
"version": null,
"labels": ["Person2"],
"removedLabels": null,
"primaryIndex": null,
"propertyList": [{
"key": "name",
"value": "jim"
}]
}
}]
然后我猜是spring数据和restapi将节点映射到Person2类bean,因为
节点的类名和标签均为Person2
。但是关系的类型是Relation2
,但是没有映射到Relation2
bean类
在这里,为什么不使用QueryResult是人与人之间的关系,有时是人与公司之间的关系,我只想编写一个api
我使用Spring Boot 2.0.4并添加neo4j lombok Web和devtool
我期望它可以返回如下所示的json:
[{
"n": {
"id": 7206,
"name": "tom",
"personProp": "someone"
},
"r": {
"id": 26,
"name": "onelink"
"r2prop":"yeyeye"
},
"m": {
"id": 21,
"name": "jim",
"personProp": "someone"
}
}]