springboot整合neo4j

springboot整合neo4j

起男 23 2025-04-23

springboot整合neo4j

依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

配置

spring:
  data:
    neo4j:
      uri: bolt://localhost:7687
      username: neo4j
      password: 123456

节点

pojo

@Data
@NodeEntity(label = "student")//节点名
public class Student{
    //id
    @Id
    @GeneratedValue
    private Long id;
    //属性
    @Property
    private String name;
}

dao

public interface StudentRepository extends Neo4jRepository<Student,Long> {//实体类,主键类型
}

关系

pojo

@Data
@RelationshipEntity(type = "studentRelation")
public class StudentRelation {
    //id
    @Id
    @GeneratedValue
    private Long id;
    //开始节点
    @StartNode
    private Student parent;
    //结束节点
    @EndNode
    private Student child;
    //具体关系
    @Property
    private String relation;
}

dao

public interface StudentRelationRepository extends Neo4jRepository<StudentRelation,Long> {
}

使用

自带API

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private StudentRelationRepository studentRelationRepository;

    @Test
    void test(){
        Student s1 = new Student();
        s1.setName("小张");
        Student s2 = new Student();
        s2.setName("小李");
        studentRepository.save(s1);
        studentRepository.save(s2);
        //关系
        StudentRelation sr1 = new StudentRelation();
        sr1.setParent(s1);
        sr1.setChild(s2);
        sr1.setRelation("朋友");
        studentRelationRepository.save(sr1);
    }

自定义方法

public interface StudentRepository extends Neo4jRepository<Student,Long> {

    @Query("match(n:student {name:{0}}),(m:student {name:{2}}) " +
            "create (n)-[:关系{relation:{1}}]->(m)")
    void createRelation(String from, String relation, String to);
}
	@Test
    void test06(){
        studentRepository.createRelation("小张","哥们","张三");
    }