neo4j-driver-java-skill
Neo4j Java Driver v6 — driver lifecycle, Maven/Gradle setup, executableQuery, executeRead/Write managed transactions, explicit transactions, async/reactive patterns, error handling, data type mapping, connection pool tuning, causal consistency/bookmarks. Use when writing Java or Kotlin code that con
By neo4j-contrib · 497 installs
npx skills add neo4j-contrib/neo4j-skills --skill neo4j-driver-java-skill
Source repository · Upstream listing
When to Use
Java/Kotlin code connecting to Neo4j (Aura or self managed)
Setting up driver, sessions, transactions in Maven/Gradle projects
Debugging result handling, error recovery, connection pool issues
Async ( CompletableFuture ) or reactive (Project Reactor / RxJava) Neo4j access
When NOT to Use
Cypher query authoring/optimization → neo4j cypher skill
Driver version upgrades → neo4j migration skill
Spring Data Neo4j ( @Node , @Relationship , Neo4jRepository ) → neo4j spring data skill
Dependency
Maven
Gradle
Check latest: https://central.sonatype.com/artifact/org.neo4j.driver/neo4j java driver
6.2.0 [2026 06]: Neo4j UUID type + Bolt 6.1 support; QueryProfile in result summary.
6.2.1 [2026 08]: fixes Value asObject() on UUID values — required if reading UUID properties generically. Neo4j 2026.07 server bundles 6.2.0.
Environment Variables
Standard pattern for connection config — never hardcode credentials:
Spring Boot: inject via @Value("${spring.neo4j.uri}") or application.properties :
Driver Lifecycle
One Driver per application — thread safe, expensive to create. Implement AutoCloseable or use try with resources.
URI schemes:
URI Use
neo4j://localhost Unencrypted, cluster routing
neo4j+s://xxx.databases.neo4j.io TLS + cluster routing (Aura)
bolt://localhost:7687 Unencrypted, single instance
bolt+s://localhost:7687 TLS, single instance
Auth options: AuthTokens.basic(u,p) · AuthTokens.bearer(token) · AuthTokens.kerberos(b64) · AuthTokens.none()
Choosing the Right API
API When Auto retry Streaming
: : : :
driver.executableQuery() Default for most queries ✅ ❌ eager
session.executeRead/Write() Large results, callback control ✅ ✅
session.beginTransaction() Multi method, external coordination ❌ ✅
session.run() Self managing queries ( CALL IN TRANSACTIONS ) ⚠️ one shot [6.1+] ✅
driver.asyncSession() Non blocking CompletableFuture ✅ ✅
driver.rxSession() Reactor/RxJava backpressure ✅ ✅
CALL { … } IN TRANSACTIONS and USING PERIODIC COMMIT self manage their transaction — use session.run() only. executableQuery and executeRead/Write will fail for these queries.
session.run() retry [6.1+]: single immediate retry on idempotent errors only (enabled by default). Disable per driver or per session:
executableQuery — Default
Never string interpolate Cypher. Always .withParameters(Map.of(...)) .
Managed Transactions ( executeRead / executeWrite )
Sessions are NOT thread safe — one per request/thread, always close.
Result must be consumed INSIDE the callback
Result is a lazy cursor tied to the open transaction. Transaction closes when callback returns — any read after that throws ResultConsumedException .
Callback rules
Consume each Result before next tx.run() — multiple open cursors = undefined behaviour.
No side effects (HTTP, email, metric increments) — callback may be retried on transient errors.
Use MERGE (idempotent), not CREATE , for retry safe writes.
executeRead → replica; executeWrite → leader.
TransactionConfig — timeouts & metadata
Explicit Transactions
Use when work spans multiple methods or requires external coordination. Not auto retried.
tx.rollback() is a network call — wrap in its own try/catch and use addSuppressed so the original exception is not lost.
Commit uncertainty : if tx.commit() throws ServiceUnavailableException , the commit may or may not have succeeded. Design writes as idempotent ( MERGE + unique constraints) so retrying is safe.
Choose explicit vs managed:
Auto retry needed → executeRead / executeWrite
Work spans multiple methods → explicit (pass tx as parameter)
Coordinating with external I/O → explicit (commit only after I/O succeeds)
Error Handling
Managed transactions auto retry TransientException — no catch needed.
Data Types & Value Extraction
Cypher type Java accessor
Integer value.asLong() / value.asInt()
Float value.asDouble()
String value.asString()
Boolean value.asBoolean()
List value.asList()
Map value.asMap()
Node value.asNode()
Relationship value.asRelationship()
Date value.asLocalDate()
DateTime value.asZonedDateTime()
Null safety — two distinct cases
Situation record.get(key) .asString()
Key present, value non null the value returns string
Key present, value is graph null Value where .isNull() = true throws Uncoercible
Key absent (typo / not projected) Value.NULL sentinel throws NoSuchElementException
Object Mapping
Map query results to Java records/classes directly — eliminates manual accessor calls.
Nested mapping — return a map projection and include COLLECT {} for lists:
Only mapped properties defined in the record are populated — extra properties returned by Cypher are ignored.
Performance Patterns
Always specify database — omitting triggers home db round trip on every call.
Route reads to replicas — RoutingControl.READ in QueryConfig or use executeRead .
Batch writes with UNWIND — pass List<Map<String,Object (plain maps only; custom objects fail):
Allowed leaf types in parameter maps: String , Long / Integer / Short / Byte , Double / Float , Boolean , List<? , Map<String,? , null . Custom objects and LocalDate must be converted first.
Group writes in one transaction — one executeWrite with a loop, not one executeWrite per iteration.
Connection pool — default 100 connections. Tune if exhausted:
Common Errors
Mistake Fix
String interpolate Cypher params .withParameters(Map.of(...)) always
Omit database name Set in QueryConfig / SessionConfig every time
New Driver per request Create once at startup; share everywhere
Share Session across threads One session per request/thread
Return Result from tx callback Collect to List / Map inside callback
Leave Result open before next tx.run() Consume before next call
Side effects in managed tx callback Move outside — callback may retry
Pass custom objects to UNWIND params Convert to List<Map<String,Object
asString() on graph null .asString("default") or check .isNull()
asString() on absent key containsKey() before optional access
Naked tx.rollback() in catch Wrap in try/catch; use addSuppressed
Assume commit() failure = no commit Commit uncertainty — design writes idempotent
Block inside async callback ( .join() ) Chain with thenCompose
Skip session close in async error path exceptionallyCompose to close then re throw
One transaction per write in loop Batch with UNWIND or group in one callback
executeWrite for a read Use executeRead — routes to replica
References
Load on demand:
[references/async reactive.md](references/async reactive.md) — full async CompletableFuture patterns, reactive RxSession with Flux.usingWhen , deadlock avoidance
[references/advanced config.md](references/advanced config.md) — full Config.builder() options, TLS, notification filtering, session level auth, user impersonation, cross session bookmarks, spatial types (Values.point/WGS 84/Cartesian)
Docs:
Java Driver manual: https://neo4j.com/docs/java manual/current/
API reference: https://neo4j.com/docs/api/java driver/current/
Checklist
[ ] One Driver instance created at startup; closed on shutdown
[ ] verifyConnectivity() called after driver creation
[ ] Database name specified in every QueryConfig / SessionConfig
[ ] Parameters used (never string interpolated Cypher)
[ ] Result consumed inside managed transaction callback
[ ] No side effects inside executeRead/Write callbacks
[ ] Sessions closed via try with resources
[ ] Async sessions closed in both success and error paths ( exceptionallyCompose )
[ ] ServiceUnavailableException on commit handled as commit uncertain
[ ] UNWIND params are List<Map<String,Object (no custom objects)
[ ] containsKey() checked before accessing optional result columns