1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| import org.neo4j.driver.*; import static org.neo4j.driver.Values.parameters;
public class Neo4jJavaDriverDemo { private static final Driver DRIVER;
static { String uri = "bolt://localhost:7687"; String username = "neo4j"; String password = "123456"; DRIVER = GraphDatabase.driver(uri, AuthTokens.basic(username, password)); }
public static void createStudent(Long id, String name, Integer age) { String cypher = "MERGE (s:Student {id: $id, name: $name, age: $age}) RETURN s"; try (Session session = DRIVER.session()) { Result result = session.run(cypher, parameters("id", id, "name", name, "age", age)); result.list().forEach(record -> System.out.println("创建学生:" + record.get("s").asMap())); } }
public static void queryStudyScore() { String cypher = "MATCH (s:Student)-[r:STUDY]->(c:Course) WHERE r.score >= $min AND r.score <= $max RETURN s.name, c.name, r.score"; try (Session session = DRIVER.session()) { Result result = session.run(cypher, parameters("min", 80, "max", 90)); result.list().forEach(record -> { String studentName = record.get("s.name").asString(); String courseName = record.get("c.name").asString(); Integer score = record.get("r.score").asInt(); System.out.printf("学生:%s,课程:%s,成绩:%d%n", studentName, courseName, score); }); } }
public static void batchCreateWithTransaction() { try (Session session = DRIVER.session()) { session.executeWrite(tx -> { tx.run("MERGE (s1:Student {id: 202405, name: '赵六', age: 21})"); tx.run("MERGE (s2:Student {id: 202406, name: '孙七', age: 20})"); tx.run("MERGE (c4:Course {id: 'C005', name: 'MySQL', credit: 3, type: '必修'})"); return null; }); System.out.println("批量创建成功,事务已提交"); } catch (Exception e) { System.out.println("批量创建失败,事务已回滚:" + e.getMessage()); } }
public static void closeDriver() { if (DRIVER != null) { DRIVER.close(); } }
public static void main(String[] args) { try { createStudent(202404L, "测试学生", 20); queryStudyScore(); batchCreateWithTransaction(); } finally { closeDriver(); } } }
|