DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Beginner's Guide To Understanding Graph Databases
  • See What's New in Neo4j 4.0
  • Designing a Blog Application Using Document Databases
  • Spring Data Neo4j: How to Update an Entity

Trending

  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • How to Convert Between PDF and TIFF in Java
  1. DZone
  2. Data Engineering
  3. Databases
  4. Introduction to Neo4j OGM

Introduction to Neo4j OGM

View this sample project that creates family members as Neo4j nodes and establishes marriage and parent-child between them.

By 
Scott Sosna user avatar
Scott Sosna
DZone Core CORE ·
Updated Jul. 17, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
10.5K Views

Join the DZone community and get the full member experience.

Join For Free

Overview

Neo4j Object-Graph Mapping, or Neo4j OGM, is a library for modifying and querying Neo4j databases without directly using Cypher.

Conceptually similar to Java Persistence API for relational databases, OGM annotations are added to plain-old Java objects, identifying them as Neo4j nodes or relationships. New objects for nodes or relationships are created and added to the Neo4j session, which OGM persists by creating and then executing the appropriate Cypher statements.

Using OGM to manipulate your Neo4j data gives you compile-time checks of nodes, relationships, labels, and properties that you don't have when working directly with Cypher but still allows your data model to evolve naturally as other NoSQL databases.

Prerequisites

  • Neo4j Server. Either Community or Enterprise, this intro tested with v3.3.1.
  • Neo4j OGM Libraries. Latest version today is v3.1.0, accessible via Maven, Gradle, and Ivy.

Sample Project

This sample project creates family members as Neo4j nodes and establishes marriage and parent-child between them. Objects are created and loaded into Neo4j via OGM without writing any Cypher.

Create Domain Objects

Nodes

A Neo4j node, also known in graph theory as a vertex, is a data record containing a random set of properties. Each POJO class is a distinct node type within the Neo4j database. They are conceptually similar to a relational database table, except they are not predefined in Neo4j before being used.

Node entity objects have a class-level annotation identifying the class as a node and an annotated member indicating the internally-generated identifier. Other properties do not require annotations if OGM can derive them automatically.

@NodeEntity
public class Person {
    @Id
    @GeneratedValue
    private Long id;

    /**
     * person's year of birth
     */
    private int birthYear;

    /**
     * Person name
     */
    private String name;
    .
    .
    .
}

Relationships

A Neo4j relationship, also known in graph theory as an arc or an edge, identifies a meaningful, directed relationship between two nodes in a graph. Neo4j OGM provides two techniques for creating relationships.

When relationship-specific properties are required to provide additional definition to the relationship, a Relationship entity object is created. Annotations define starting and ending nodes in the relationship; other properties do not require annotations if OGM can derive them automatically.

@RelationshipEntity(type = "MARRIED")
public class Married {

    /**
     * Internal Neo4J id of the node
     */
    @Id
    @GeneratedValue
    private Long id;

    /**
     * If divorced, what year was the divorce finalized
     */
    private Integer yearDivorced;

    /**
     * the year married
     */
    private Integer yearMarried;

    /**
     * the wife in the marriage
     */
    @StartNode
    private Person wife;

    /**
     * the husband in the marriage
     */
    @EndNode
    private Person husband;
    .
    .
    .
}

Relationships can also be identified in the Node class if no relationship-specific properties are required using a collection of Nodes. Multiple relationships of different types can be defined this way.

@NodeEntity
public class Person {
    @Id
    @GeneratedValue
    private Long id;
    .
    .
    .
    @Relationship(type = "PARENT")
    private List<Person> children = null;
    .
    .
    .
}

Load Data

Configure Session

A session is configured by declaring how to connect and authenticate to your Neo4j database and identifying the packages containing the domain objects. Domain objects in other packages are not recognized by OGM and are not persisted to the database.

public class Loader {

    /**
     * Session factory for connecting to Neo4j database
     */
    private final SessionFactory sessionFactory;

    //  Configuration info for connecting to the Neo4J database
    static private final String SERVER_URI = "bolt://localhost";
    static private final String SERVER_USERNAME = "neo4j";
    static private final String SERVER_PASSWORD = "password";


    /**
     * Constructor
     */
    public Loader() {
        //  Define session factory for connecting to Neo4j database
        Configuration configuration = new Configuration.Builder().uri(SERVER_URI).credentials(SERVER_USERNAME, SERVER_PASSWORD).build();
        sessionFactory = new SessionFactory(configuration, "com.buddhadata.sandbox.neo4j.ogm.intro.node", "com.buddhadata.sandbox.neo4j.ogm.intro.relationship");
    }
    .
    .
    .
}

Open Session and Transaction

Similar to JPA, you open a new session to Neo4j database and create a transaction in which your work exists.

Warning: For demo purposes, this demo project purges the database in each run; obviously you wouldn't do this in a production environment!

public class Loader {
    .
    .
    .
    private void process () {

        //  For demo purposes, create session and purge to cleanup whatever you have
        Session session = sessionFactory.openSession();
        session.purgeDatabase();

        //  All work done in single transaction.
        Transaction txn = session.beginTransaction();
        .
        .
        .
    }
}

Persist Data

Create the needed Node and Relationship objects and save them in the OGM session. Once all objects are passed to the session, commit the transaction.

public class Loader {
    .
    .
    .
    private void process () {
        .
        .
        .
        Person Carol = new Person ("Carol Maureen", 1945);
        Person Courtney = new Person ("Courtney Janice", 1945);
        Person Jeremy = new Person ("Jeremy Douglas", 1969);
        Person Mike = new Person ("Michael Blevins", 1945);
        Person Scott = new Person ("Scott Christoper", 1965);

        List<Person> children = Carol.getChildren();
        children.add (Scott);
        children.add (Courtney);
        children.add (Jeremy);
        children = Mike.getChildren();
        children.add (Scott);
        children.add (Courtney);
        children.add (Jeremy);

        session.save (Carol);
        session.save (Courtney);
        session.save (Jeremy);
        session.save (Mike);
        session.save (Scott);

        session.save (new Married(Carol, Mike, 1964, 1973));

        txn.commit();
    }
}

Check Work

In your browser, navigate to your Neo4j server and execute the following Cypher statement to return all nodes created.

MATCH (s) RETURN s

Conclusion

Hopefully, you now understand the basic concepts of Neo4j OGM and can use it in your own use cases.

The complete demo project can be downloaded from here.

Neo4j Database Relational database

Opinions expressed by DZone contributors are their own.

Related

  • The Beginner's Guide To Understanding Graph Databases
  • See What's New in Neo4j 4.0
  • Designing a Blog Application Using Document Databases
  • Spring Data Neo4j: How to Update an Entity

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!