Bootstrap

Spring Boot应用程序集成Neo4j

以下是一个简单的Spring Boot应用程序,集成Neo4j实现插入和查询数据的示例。我们将使用Spring Data Neo4j来简化与Neo4j数据库的交互。

docker compose 安装 Neo4j

使用docker compose 安装并启动 Neo4j:

neo4j-docker-compose.yml 文件内容:

version: '3.9'
services:

  neo4j:
    image: neo4j:5.9.0-community
    volumes:
      - ./conf:/var/lib/neo4j/conf
      - ./import:/var/lib/neo4j/import
      - ./plugins:/plugins
      - ./data:/data
      - ./logs:/var/lib/neo4j/logs
    restart: always
    ports:
      - 7474:7474
      - 7687:7687
    environment:
      - NEO4J_AUTH=neo4j/0123456789 #修改默认用户密码,这里的密码在neo4j:5.9.0需要较长的密码要求,不然启动不成功

启动容器:

docker compose -f neo4j-docker-compose.yml up -d

创建Spring Boot项目

首先,确保你在项目的pom.xml文件中添加了以下依赖:

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Data Neo4j -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-neo4j</artifactId>
        </dependency>

        <!-- Lombok (可选) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.12.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

配置Neo4j连接

application.properties文件中添加Neo4j相关的配置:

spring.data.neo4j.uri=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=yourpassword

创建实体类

  1. 创建一个简单的实体类来表示Neo4j中的节点:
package com.example.neo4jdemo.model;

import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;

@NodeEntity("Person")
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    @Property("name")
    private String name;

    @Property("age")
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  1. 创建一个简单的实体关系类来表示Neo4j中的关系:
package com.example.neo4jdemo.model;

import lombok.Data;
import org.neo4j.ogm.annotation.*;


import java.io.Serializable;

@Data
@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;
    }
}

创建仓库接口

  1. 创建一个仓库接口来定义实体数据访问操作:
package com.example.neo4jdemo.repository;

import com.example.neo4jdemo.model.Person;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends Neo4jRepository<Person, Long> {

    List<Person> findByName(String name);
}
  1. 创建一个仓库接口来定义关系数据访问操作:
package com.example.neo4jdemo.repository;

import com.example.neo4jdemo.model.PersonRelation;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRelationRepository extends Neo4jRepository<PersonRelation,Long> {

}

创建服务层

创建一个服务层来封装业务逻辑:

package com.example.neo4jdemo.service;

import com.example.neo4jdemo.model.Person;
import com.example.neo4jdemo.repository.PersonRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class PersonService {

    private final PersonRepository personRepository;

    public Person savePerson(Person person) {
        return personRepository.save(person);
    }

    public List<Person> findByName(String name) {
        return personRepository.findByName(name);
    }
}

创建控制器

创建一个控制器来处理HTTP请求:

package com.example.neo4jdemo.controller;

import com.example.neo4jdemo.model.Person;
import com.example.neo4jdemo.service.PersonService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/persons")
@RequiredArgsConstructor
public class PersonController {

    private final PersonService personService;

    @PostMapping
    public Person savePerson(@RequestBody Person person) {
        return personService.savePerson(person);
    }

    @GetMapping("/{name}")
    public List<Person> findByName(@PathVariable String name) {
        return personService.findByName(name);
    }
}

创建测试类

创建一个测试类来处理生成实体和关系数据:


import com.example.neo4jdemo.Neo4jDemoApplication;
import com.example.neo4jdemo.model.Person;
import com.example.neo4jdemo.model.PersonRelation;
import com.example.neo4jdemo.repository.PersonRelationRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(classes = Neo4jDemoApplication.class)
class SpringbootNeo4jApplicationTests {

    @Autowired
    private PersonRelationRepository personRelationRepository;

    @Test
    void nodeRelation(){
        Person p1 = new Person("唐僧",4321);
        Person p2 = new Person("孙悟空",3421);
        Person p3 = new Person("猪八戒",2413);
        Person p4 = new Person("沙僧",1234);

        PersonRelation pr1 = new PersonRelation(p1,p2,"徒弟");
        PersonRelation pr2 = new PersonRelation(p1,p3,"徒弟");
        PersonRelation pr3 = new PersonRelation(p1,p4,"徒弟");

        personRelationRepository.save(pr1);
        personRelationRepository.save(pr2);
        personRelationRepository.save(pr3);
    }
}

Spring Boot 主类

创建Spring Boot应用程序的主类:

package com.example.neo4jdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Neo4jDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(Neo4jDemoApplication.class, args);
    }
}

运行应用程序

启动Spring Boot应用程序。你可以使用Postman或其他HTTP客户端来测试API:

插入数据:

POST http://localhost:8080/persons
Body (JSON):

{
  "name": "John Doe",
  "age": 30
}
查询数据:

GET http://localhost:8080/persons/John%20Doe

数据库查看:

访问地址:http://127.0.0.1:7474/browser/

结果展示:
在这里插入图片描述

解释

  • 依赖管理

    • 使用Spring Boot Starter Web简化Web应用开发。
    • 使用Spring Data Neo4j简化与Neo4j数据库的交互。
  • 配置

    • application.properties中指定Neo4j服务器的地址和认证信息。
  • 实体类

    • 定义一个简单的Person实体类,使用注解来映射Neo4j节点。
  • 仓库接口

    • 使用Spring Data Neo4j的仓库接口来定义数据访问操作。
  • 服务层

    • 封装业务逻辑,提供保存和查询Person对象的高层接口。
  • 控制器

    • 处理HTTP请求,提供RESTful API进行数据插入和查询。

通过这个示例,你可以轻松地使用Spring Boot集成Neo4j来实现数据的插入和查询功能。

;