Using Java to Operate Neo4j
To use Java to operate Neo4j, you first need to add Neo4j's Java driver dependency. The following is an example pom.xml file built using Maven, which contains Neo4j's Java driver dependencies:
<dependencies>
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>
After adding dependencies, you can start writing Java code to operate Neo4j.
The following is a complete Java code example, including operations for data insertion, modification, query, and deletion:
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.TransactionWork;
import static org.neo4j.driver.Values.parameters;
public class Neo4jExample {
public static void main(String[] args) {
String uri=“ bolt://localhost:7687 The URI of the Neo4j database
String user="your username"// The username of the Neo4j database
String password="your password"// Password for Neo4j database
//Creating Driver Objects
try (Driver driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password))) {
//Create Session Object
try (Session session = driver.session()) {
//Execute transactions
session.writeTransaction(new TransactionWork<Void>() {
@Override
public Void execute(Transaction tx) {
//Create nodes
tx.run("CREATE (n:Person {name: $name, age: $age})", parameters("name", "John", "age", 30));
//Query nodes
tx.run("MATCH (n:Person) WHERE n.name = $name RETURN n.age", parameters("name", "John"))
.single()
.get("n.age")
.asInt();
//Modify nodes
tx.run("MATCH (n:Person) SET n.age = $newAge WHERE n.name = $name",
parameters("name", "John", "newAge", 40));
//Delete Node
tx.run("MATCH (n:Person) WHERE n.name = $name DELETE n",
parameters("name", "John"));
return null;
}
});
}
}
}
}
In the above example, we first created a driver object, then created a session object, and then executed a transaction that includes node creation, query, modification, and deletion operations.
Please note that before using the actual Neo4j database, make sure to replace the URI, username, and password with the actual values.
In addition, it is necessary to modify the query statements and parameters according to actual needs.