Developer Guides Getting Started Getting Started What is a Graph Database? Intro to Graph DBs Video Series Concepts: RDBMS to Graph Concepts: NoSQL to Graph Getting Started Resources Neo4j Graph Platform Graph Platform Overview Neo4j Desktop Intro Neo4j Browser Intro… Read more →

Developer Guides

Want to Speak? Get $ back.

Using Neo4j from Java

Goals
If you are a Java developer, this guide provides an overview of options for connecting to Neo4j. While this guide is not comprehensive, it will introduce the different APIs and link to the relevant resources.
Prerequisites
You should be familiar with the graph database concepts and the property graph model. Having installed Neo4j and tried out our Cypher Query language helps too. When developing with Neo4j, please use Java 8 or 11 and your favorite IDE.
Intermediate

Neo4j for Java Developers

java

Neo4j offers a rich set of integration possibilities for developers using Java or other JVM-languages.

The standalone Neo4j Server can be installed on any machine and then accessed via its binary “Bolt” protocol through our official driver or any bolt-enabled drivers.

You can also extend Neo4j by implementing user defined procedures for Cypher in Java or other JVM languages.

Please note that starting with version 3.0 you need Java 8 to use Neo4j Server.

The Example Project

The Neo4j example project is a small, one page webapp for the movies database built into the Neo4j tutorial. The front-end page is the same for all drivers: movie search, movie details, and a graph visualization of actors and movies. Each backend implementation shows you how to connect to Neo4j from each of the different languages and drivers.

You can learn more about our small, consistent example project across many different language drivers here. You will find the implementations for all drivers as individual GitHub repositories, which you can clone and deploy directly.

Neo4j Java Driver

The Neo4j Java driver is officially supported by Neo4j and connects to the database using the binary protocol. It aims to be minimal, while being idiomatic to Java. We support Java 8 and 11 for the driver.

When using Maven, add this to your pom.xml file:

<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.7.2</version>

For Gradle or Grails, this is how to add the dependency:

compile 'org.neo4j.driver:neo4j-java-driver:1.7.2'

For other build systems, see information available at Maven Central.

import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;

import static org.neo4j.driver.v1.Values.parameters;

public class HelloWorldExample implements AutoCloseable
{
    private final Driver driver;

    public HelloWorldExample( String uri, String user, String password )
    {
        driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
    }

    @Override
    public void close() throws Exception
    {
        driver.close();
    }

    public void printGreeting( final String message )
    {
        try ( Session session = driver.session() )
        {
            String greeting = session.writeTransaction( new TransactionWork<String>()
            {
                @Override
                public String execute( Transaction tx )
                {
                    StatementResult result = tx.run( "CREATE (a:Greeting) " +
                                                     "SET a.message = $message " +
                                                     "RETURN a.message + ', from node ' + id(a)",
                            parameters( "message", message ) );
                    return result.single().get( 0 ).asString();
                }
            } );
            System.out.println( greeting );
        }
    }

    public static void main( String... args ) throws Exception
    {
        try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
        {
            greeter.printGreeting( "hello, world" );
        }
    }
}

Name

Version

Authors

neo4j-java-driver

1.7.2

The Neo4j Team

Package

Example

Neo4j Online Community

Docs

API

Source

Spring Data Neo4j

sdn

Neo4j’s Spring Data integration was the founding project of the Spring Data efforts, started by Rod Johnson and Emil Eifrem. Spring Data Neo4j was recently rewritten to incorporate the many improvements in Neo4j and Cypher but also in the Spring Data ecosystem.

It integrates tightly with the Spring Framework and offers Object-Graph mapping on top of Neo4j.

Features (based on Neo4j-OGM):

  • Spring Boot Integration
  • annotation based object graph mapping
  • interface based repository support with annotated and derived finder methods
  • fast class metadata scanning
  • optimized management of data loading and change tracking for minimal data transfers
  • multiple transports: binary protocol, HTTP and embedded
  • persistence lifecycle events

More detail can be found on the dedicated Spring Data Neo4j page.

Object-Graph-Mapping with Neo4j-OGM

Developing Java Business Applications often requires mapping rich domain models to your database. The Neo4j-OGM library is a pure Java library that can persist (annotated) domain objects using Neo4j. It uses Cypher statements to handle those operations in Neo4j.

The OGM supports tracking changes to minimize necessary updates and transitive persistence (reading and updating neighborhoods of an object).

The connection to Neo4j handled by a driver layer, which can use the binary protocol, HTTP or Neo4j’s embedded APIs.

Authors

The Neo4j and GraphAware Teams

Package

http://maven.org

Source

https://github.com/neo4j/neo4j-ogm

Docs

https://neo4j.com/docs/ogm-manual/current/introduction/

Article

https://neo4j.com/blog/neo4j-java-object-graph-mapper-released/

Example

https://github.com/neo4j-examples/neo4j-ogm-university

More detail can be found on the dedicated Neo4j OGM page.

User-Defined Procedures and Functions

User Defined Procedures and Functions are available within Cypher and encapsulate dedicated functionality.

Just by annotating methods of a Java class and deploying the resulting jar file into your Neo4j installation, you can make new functionality easily available within the query language.

To implement your procedures or functions you would use the Neo4j Embedded Java API. Besides an object-oriented API to the graph database, working with Node, Relationship, and Path objects, it also offers highly customizable, high-speed traversal- and graph-algorithm implementations.

We don’t provide code examples for the Java API on this page, because they are covered in detail in the Java developers manual.

Neo4j uses that functionality itself for built-in procedures for meta-data, cluster-, query- and user-management and more.

Several libraries already provide new capabilities using procedures and functions, here is an example from the APOC library.

MATCH (start:City {name: 'Berlin'}),(end:City {name: 'Malmö'})
CALL apoc.algo.dikjstra(start, end, "ROUTE","distance") yield path, weight
RETURN path
ORDER BY weight ASC LIMIT 10

To get you started we provided a template project and documentation in the Java developer manual.

More useful examples for user defined procedures can be found in our procedure & function gallery.

Using Neo4j Server with JDBC

Being a Java developer you’re probably familiar with JDBC as a way to work with relational databases, either directly or via abstractions like Spring’s JDBCTemplate or MyBatis. Many tools for ETL, Report Generators, Business Intelligence, and data management also use JDBC drivers to interact with relational databases.

As Cypher, like SQL, is a textual parametrizable query language that can return tabular results, it was possible for us to support the JDBC APIs and make a Neo4j-JDBC driver available.

The driver supports the new binary “Bolt” protocol of Neo4j 3.x, the transactional http endpoint and Neo4j embedded connections.

// Connect
Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost");

// Querying
try (Statement stmt = con.createStatement()) {
    ResultSet rs = stmt.executeQuery("MATCH (n:User) RETURN n.name");
	while (rs.next()) {
		System.out.println(rs.getString("n.name"));
	}
}
con.close();

More details on how to use it can be found with our example project for Java-JDBC. There, we implement the backend as a minimal Java webapp that leverages Neo4j-JDBC to connect to Neo4j Server.

We tested the driver with many enterprise tools to ensure that it works in a variety of environments. Just grab the JAR of the latest release and add it to your tool of choice.

Authors

Developers from Larus BA Italy and Neo4j

Package

https://github.com/neo4j-contrib/neo4j-jdbc/releases/latest

Source

https://github.com/neo4j-contrib/neo4j-jdbc

Docs

https://github.com/neo4j-contrib/neo4j-jdbc/blob/master/README.adoc

Example

https://github.com/neo4j-examples/movies-java-jdbc

Blog Post

http://neo4j.com/blog/couchbase-jdbc-integrations-neo4j-3-0/

Neo4j Community Drivers

The drivers below have been thankfully contributed by the Neo4j community. Many of these are fully featured and well maintained. But we don’t take any responsibility for their fitness for use with the most recent versions of Neo4j.

JCypher

JCypher provides seamlessly integrated Java access to Neo4j at different levels of abstraction:

At the topmost level of abstraction, JCypher allows you to map complex business domains to graph databases. You can take an arbitrarily complex graph of domain objects or POJOs and store it in a straightforward way into Neo4j for later retrieval. You do not need to modify your domain object classes in any way, there is also no need for annotations. JCypher provides a default mapping out of the box.

At the same level of abstraction, Domain Queries provide the power and expressiveness of queries on a graph database, while being formulated on domain objects or on types of domain objects, respectively. The true power of Domain Queries comes from the fact, that the graph of domain objects is backed by a graph database.

At the next lower level of abstraction – access to graph databases – is provided based on a generic graph model. While simple, the model allows you to easily navigate and manipulate graphs.

At the bottom level of abstraction, a native Java DSL in the form of a fluent Java API allows you to intuitively and comfortably formulate queries against Neo4j.

Author

Wolfgang Schützelhofer

Package

http://maven.org

Source

http://github.com/Wolfgang-Schuetzelhofer/jcypher

Docs

http://jcypher.iot-solutions.net/

Article

https://neo4j.com/blog/jcypher-focus-on-your-domain-model-not-how-to-map-it-to-the-database/

Groovy & Grails: Neo4j Grails Plugin

grails

The goal of GORM for Neo4j is to provide a ‘as-complete-as-possible’ GORM implementation that maps domain classes and instances to the Neo4j nodespace. The following features are supported:

  • Marshalling from Neo4j Nodes to Groovy types and back again
  • Support for GORM dynamic finders, criteria and named queries
  • Session-managed transactions
  • Access to Neo4j’s traversal capabilities
  • Access the Neo4j graph database in all flavours (Embedded, REST and HA)

Authors

Stefan Armbruster, Graeme Rocher

Package

http://www.grails.org/plugin/neo4j

Source

https://github.com/grails/grails-data-mapping/tree/master/grails-datastore-gorm-neo4j

Docs

http://grails.github.io/grails-data-mapping/latest/neo4j/

Scala: neotypes

scala

Scala lightweight, type-safe, asynchronous driver (not opinionated on side-effect implementation) for neo4j. The project aims to provide seamless integration with most popular scala infrastructures such as lightbend (Akka, Akka-http, Lagom, etc), typelevel (cats, http4s, etc), twitter (finch, etc)…​

Author

Dmitry Fedosov

Source

https://github.com/neotypes/neotypes

Docs

https://neotypes.github.io/neotypes/docs.html

Article

http://dimafeng.com/2018/12/27/neotypes-1/

Example

https://github.com/neotypes/examples

JPA: Hibernate OGM

Hibernate Object/Grid Mapper (OGM) with Neo4j Support.

Authors

Davide D’Alto, Gunnar Moelling, Emmanuel Bernard

Package

http://maven.org

Source

https://github.com/hibernate/hibernate-ogm/tree/master/neo4j

Docs

http://docs.jboss.org/hibernate/ogm/5.0/reference/en-US/html_single/#ogm-neo4j

Article

Blog, JPL Queries

Example

https://github.com/TimmyStorms/hibernate-ogm-neo4j-example