How to integrate Neo4j with Spring Boot for storing and querying graph data

To set up a simple Spring Boot project with Spring Data Neo4j, follow the steps below. This example demonstrates how to integrate Neo4j with Spring Boot for storing and querying graph data.


1. Set up the Project

Using Spring Initializr:

You can create a Spring Boot project using Spring Initializr with the following options:

  • Project: Maven
  • Language: Java
  • Spring Boot version: 3.4.1 (or the latest 3.x version available)
  • Dependencies:
    • Spring Data Neo4j
    • Spring Web
    • Neo4j Driver (this should be automatically included with spring-boot-starter-data-neo4j)

Alternatively, you can manually set up the Maven pom.xml for your Spring Boot project.

2. Add Dependencies to pom.xml

Add the following dependencies for Spring Boot 3.4.1 and Spring Data Neo4j.

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- Spring Boot DevTools for easier development (optional) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Make sure the spring-boot-starter-data-neo4j dependency is included as it brings the necessary Neo4j integration.

3. Configure Neo4j Connection in application.properties

In the src/main/resources/application.properties (or application.yml), configure the connection to your Neo4j instance.

# Neo4j connection details
spring.data.neo4j.uri=bolt://localhost:7687
spring.data.neo4j.username=neo4j
spring.data.neo4j.password=password
spring.data.neo4j.database=neo4j

Make sure that the URI, username, password, and database settings match your Neo4j setup.

4. Create a Domain Model

In this step, you'll define a simple domain model using the @NodeEntity annotation to define a Person entity.

import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;

@NodeEntity
public class Person {

    @GraphId
    private Long id;

    private String name;

    @Relationship(type = "FRIEND_OF", direction = Relationship.UNDIRECTED)
    private Person friend;

    // 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 Person getFriend() {
        return friend;
    }

    public void setFriend(Person friend) {
        this.friend = friend;
    }
}

This example models a simple Person node, with a relationship to another Person node, representing a "friend" relationship.

5. Create a Repository Interface

Next, create a repository interface extending Neo4jRepository to interact with the Person entities.

import org.springframework.data.neo4j.repository.Neo4jRepository;

public interface PersonRepository extends Neo4jRepository<Person, Long> {

    Person findByName(String name);
}

This interface will allow you to interact with the Neo4j database and query the Person nodes.

6. Service Layer (Optional)

It’s a good practice to add a service layer to encapsulate business logic.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonService {

    @Autowired
    private PersonRepository personRepository;

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

    public Person findPersonByName(String name) {
        return personRepository.findByName(name);
    }
}

This service exposes methods to save and find Person entities by their name.

7. Create a Controller (Optional)

If you want to expose a REST API, create a controller to handle HTTP requests.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;

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

    @GetMapping("/person")
    public Person getPerson(@RequestParam String name) {
        return personService.findPersonByName(name);
    }
}

This controller provides endpoints to create and retrieve Person entities.

8. Run the Application

Run your Spring Boot application by executing the following command:

mvn spring-boot:run

This will start the application, and it will connect to your Neo4j database.

9. Example Interactions

Now that everything is set up, you can interact with your Neo4j database through REST API endpoints:

  1. Add a Person: You can create a person via POST request:

    curl -X POST -H "Content-Type: application/json" -d '{"name": "Alice"}' http://localhost:8080/person
    
  2. Get a Person: Retrieve the person by their name:

    curl "http://localhost:8080/person?name=Alice"

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example