Neo4j - OGM Object Graph Mapper - Developer Guides
1、pom依赖:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-neo4j</artifactId>
<version>6.0.14</version>
</dependency>
2、yml配置:
spring:
data:
neo4j:
uri: bolt://192.168.10.35:7687
username: neo4j
password: dengtacj@2021
注意:neo4j使用版本为:4.3.5,springboot对应版本为2.4.7, spring-data-neo4j 对应版本为6.0.14.大于6.0.4版本启动时会报错,暂未解决。
初始化查询时,有两种方式,其中Neo4jTemplate必须指定对应的返回类,而且类必须和Neo4j中的对应,并需要继承实现。否则会报如下错误:Could not find mappable nodes or relationships inside Record<{dt_code: "0001000009", stock_code: "000009"}> for org.springframework.data.neo4j.core.mapping.DefaultNeo4jPersistentEntity@7a18288b。
原因如下: know that this sounds ridiculous first but with choosing the repository abstraction, you say that everything that should get processed during the mapping phase is a Node
and you want to project its properties (or a subset) into the POJO (DTO projection). SDN cannot ensure that you are really working with the right type when it starts the mapping, so it throws the exception you are facing. Neo4j-OGM was more relaxed behind the scenes for mapping the @QueryResult
s but unfortunately also wrong with this direction.来源:java - Replace @QueryResult while switching from SDN+OGM to SDN/RX - Stack Overflow
故强烈建议使用Neo4jClient。
在需要的地方注入:
@Autowired
Neo4jClient client;
实体内容解析如下(对于变关系解析,使用到时补充):
SearchResultData searchResultData = new SearchResultData();
try {
Neo4jClient.RunnableSpec result = client.query(conditions);
Collection<Map<String, Object>> result1 = result.fetch().all();
ArrayList<SimpleSearchIndex> finalResult = new ArrayList<>();
result1.forEach(each -> {
try {
SimpleSearchIndex neo4ja = new SimpleSearchIndex();
if (null != each.get("keyid")) {
neo4ja.setKeyid(String.valueOf(each.get("keyid")));
}
if (null != each.get("data_type")) {
neo4ja.setData_type(Integer.parseInt(String.valueOf(each.get("data_type"))));
}
finalResult.add(neo4ja);
} catch (Exception e) {
log.error("parse neo4j result to SimpleSearchIndex error, error msg is " + e.getMessage());
}
});
}
catch(Exception e){
log.error("post search neo4j error, error msg is "+ e.getMessage());
}