Spring Boot整合neo4j
spring-data-neo4j
版本:springboot 2.3.5 spring-data-neo4j:5.3.5
https://docs.spring.io/spring-data/neo4j/docs/5.3.5/reference/html/#getting-started
添加neo4j依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
添加配置
(注意:不同版本依赖配置可能不一样),可通过neo4j自动配置类查看
# neo4j配置
spring.data.neo4j.uri= bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=12345
创建实体
@NodeEntity:标明是一个节点实体 @RelationshipEntity:标明是一个关系实体 @Id:实体主键
@Property:实体属性 @GeneratedValue:实体属性值自增 @StartNode:开始节点(可以理解为父节
点) @EndNode:结束节点(可以理解为子节点)
import lombok.Data;
import java.io.Serializable;
@Data
@Builder
@NodeEntity("person")
public class Person implements Serializable {
@Id
@GeneratedValue
private Long id;
@Property("name")
private String name;
}
@Data
@NoArgsConstructor
@RelationshipEntity(type = "徒弟")
public class PersonRelation implements Serializable {
@Id
@GeneratedValue
private Long id;
@StartNode
private Person parent;
@EndNode
private Person child;
@Property
private String relation;
public PersonRelation(Person parent, Person child, String relation) {
this.parent = parent;
this.child = child;
this.relation = relation;
}
}
创建接口继承Neo4jRepository
/*** @author Fox */
@Repository
public interface PersonRelationRepository extends Neo4jRepository<PersonRelation, Long> {
}
@Repository
public interface PersonRepository extends Neo4jRepository<Person, Long> {
/*** 查询某个节点的所有子节点 * @param pId * @return */
@Query("Match (p:person) -[*]->(s:person) where id(p)={0} return s")
List<Person> findChildList(Long pId);
@Query("Match (p:person {name:{0}}) -[*]->(s:person) return s")
List<Person> findChildList(String name);
/**
* 查询当前节点的父节点 * @param name * @return
*/
@Query("Match (p:person) -[*]->(s:person {name:{0}}) return p")
List<Person> findParentList(String name);
}