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.
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.
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.
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.
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.
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.
This controller provides endpoints to create and retrieve Person entities.
8. Run the Application
Run your Spring Boot application by executing the following command:
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:
Add a Person: You can create a person via POST request:
Get a Person: Retrieve the person by their name:

Comments
Post a Comment