Graph databases like Neo4j provide a powerful way to store, query, and analyze complex, interconnected data. If you're new to graph programming, Java is an excellent language to start with, given its wide use and extensive libraries. Let's explore a simple yet insightful graph example using the Spring Boot framework with the Neo4j Java driver.

First, add Neo4j driver and Spring Boot dependencies to your `build.gradle` or `pom.xml` file. For Gradle, include `org.neo4j:neo4jdriver` and `org.springframework.boot:spring-boot-starter-web`; for Maven, use `neo4j drivers` artifact and `spring-boot-starter-web`.

Setting Up the Project and Database
The first step is to establish a connection to your Neo4j instance. Use the following code snippet to set up a `Session` object with a `GraphDatabaseService`.

```java import org.neo4j.driver.Session; import org.neo4j.driver.GraphDatabase; ... Session session = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "password" ) ).session(); ```
Defining Nodes and Relationships

Now, let's define two node labels, `:Person` and `:Movie`, and a relationship `:ACTED_IN`. We'll create nodes and relationships using the `CREATE` clause.
```cypher CREATE (p1:Person {name: 'Tom Hanks'}) CREATE (p2:Person {name: 'Meg Ryan'}) CREATE (m:Movie { title: 'Sleepless in Seattle'}) CREATE (p1)-[:ACTED_IN]->(m) CREATE (p2)-[:ACTED_IN]->(m) ```
Querying the Graph
![12 Best Free Udemy Courses to Learn Data Structure and Algorithms in Java, Python, and C++ in 2025 [UPDATED]](https://i.pinimg.com/originals/de/14/80/de1480cbe31191880a229eb26d47638f.png)
With the graph structure in place, we can query it using Cypher. Let's find all movies that 'Tom Hanks' acted in.
```java try (Session session = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic("neo4j", "password")).session()) { String query = "MATCH (p:Person {name: 'Tom Hanks'})-[ACTED_IN]->(m:Movie) RETURN m.title"; System.out.println(session.run(query).list()); } ```
Importing Data from CSV

For larger datasets, importing data from CSV files can be more efficient. We'll use the `LOAD CSV` command to import actors and movies data.
```cypher LOAD CSV WITH HEADERS FROM "file:///import/actors.csv" AS csv CREATE (p:Person { name: csv.name, born: toInteger(csv.born), died: toInteger(csv.died) }) ```



















Working with Relationships
After creating nodes, we can connect them using the `MATCH`, `MERGE`, and `CREATE` clauses.
```cypher MATCH (a:Person {name: 'Tom Hanks'}), (b:Person {name: 'Meg Ryan'}) MERGE (a)-[:ACTED_IN]->(b) ```
With this example, we've explored creating a simple graph using Neo4j's Java driver, querying the graph, and importing data from CSV files. Graph databases offer immense potential for analyzing complex networks, and Java provides the perfect platform to leverage this power.