原生API
待补充。。。
SpringBoot整合Neo4j
参考
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-Neo4j</artifactId>
</dependency>
配置
spring:
data:
neo4j:
uri: bolt://127.0.0.1:7687
username: neo4j
password: neo4j
类似于jpa
模式,同样是构建 model 层、repository 层,然后在此基础上操作自定义或模板方法。
实体类
节点
@Data
@NodeEntity(label = "Node")
public class Node {
@Id
@GeneratedValue
private Long id;
@Property(name = "name")
private String name;
@Property(name = "title")
private String title;
}
关联关系类
@Data
@RelationshipEntity(type = "DOWNSTREAM_OF")
public class DownstreamOfRelationShip {
@Id
@GeneratedValue
private Long id;
@StartNode
private Node startNode;
@EndNode
private Node endNode;
@Property("relation_ship_id")
private String relationShipId;
}
@Data
@RelationshipEntity(type = "SON_OF")
public class SonOfRelationShip {
@Id
@GeneratedValue
private Long id;
@StartNode
private Node startNode;
@EndNode
private Node endNode;
@Property("relation_ship_id")
private String relationShipId;
}
使用
第一种直接返回关系类
dao层
@Repository
public interface NodeRepository extends Neo4jRepository<Node,Long> {
@Query("MATCH p=(n:Node) RETURN p")
List<Node> selectAll();
@Query("MATCH(p:Node{name:{name}}) return p")
Node findByName(String name);
@Query("MATCH DownstreamOfRelationShip = (c:Node)-[r]->(p:Node) where type(r) = {relationName} return DownstreamOfRelationShip ")
List<DownstreamOfRelationShip> findRelationship(@Param("relationName") String relationName);
}
第二种返回自定义类
定义一个类Relationship ,这里要注意,需要在类上添加注解@QueryResult,代表了Neo4j查询结果返回的类,注解不加的话会接收不到返回数据。
自定义类
@Data
@QueryResult
public class RelationShip {
@Id
@GeneratedValue
private Long id;
@StartNode
private Node startNode;
@EndNode
private Node endNode;
@Property("relation_ship_id")
private String relationShipId;
@Property("relation_ship_type")
private String relationShipType;
}
dao层
@Repository
public interface NodeRepository extends Neo4jRepository<Node,Long> {
@Query("MATCH data=(endNode:Node{id:$endNodeId})<-[line:SON_OF|DOWNSTREAM_OF*1..]-(startNode) UNWIND line as linel with DISTINCT linel RETURN startNode(linel) as startNode ,endNode(linel) as endNode,id(linel) as id,type(linel) as relation_ship_type,linel.relation_ship_id as relation_ship_id ")
List<RelationShip> findTopologyByDeviceId(@Param("endNodeId") String endNodeId);
}
参考:https://www.modb.pro/db/55683
service
@Slf4j
@Service
public class NodeServiceImpl implements NodeService {
@Autowired
private NodeRepository nodeRepository;
@Override
public Node addNode(Node node) {
Node node = nodeRepository.save(node);
return node ;
}
public Node findNode(String name) {
Node node = nodeRepository.findByName(name);
return node;
}
}