Object Graph Mapping with Neo4j-OGM

Neo4j - the open-source graph database, released its own Java Object Graph Mapper recently. Developing Java Business Applications often requires mapping domain object networks to your database. The Neo4j-OGM library is a pure Java library that can store, read and query (annotated) domain objects using Neo4j. It uses Cypher statements execute those operations with Neo4j Server. Earlier Java objects were mapped with Neo4j entities using Spring Data Neo4j 4.0. According to Neo4j's blog, Neo4j-OGM becomes their official library for Object Graph Mapping.
This tutorial helps you to develop a very simple Hello World application using Neo4j-OGM library.


Step 1:
Create a new Java project in Eclipse and name it as "Neo4J OGM HelloWorld"

Step 2:
This tutorial uses Maven to add  Neo4J OGM library. If you prefer, you can import the Neo4j-OGM library manually.
To convert the project to Maven project, right click on the project and select ConfigureConvert to Maven Project.


Step 2.1:
Add the following dependency to the pom.xml file.
<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j-ogm</artifactId>
    <version>1.1.3</version>
</dependency>

Step 3:
Create a new package "com.javahelps.ogmhelloworld" and create a new class Main.java inside that package.

Step 4:
Create another package "com.javahelps.ogmhelloworld.entities" and create two classes: Student.java and Course.java. These two classes are used to map the Neo4j entities to Java objects.

Step 5:
Modify the Course.java as shown below:
package com.javahelps.ogmhelloworld.entities;

import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;

@NodeEntity
public class Course {

    @GraphId
    private Long id;

    private String name;

    private float credits;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getCredits() {
        return credits;
    }

    public void setCredits(float credits) {
        this.credits = credits;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Course other = (Course) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}
In this code, the @NodeEntity annotation is used to define the class as an entity. The @GraphId annotation defines the property which will be used to store the auto generated ids of each entities.

The hashCode and equals method are overridden, since the objects of Course class are stored in java.util.HashSet, later in this project.

Step 6:
Modify the Student.java as shown below:
package com.javahelps.ogmhelloworld.entities;

import java.util.HashSet;
import java.util.Set;

import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;

@NodeEntity
public class Student {

    @GraphId
    private Long id;

    private String name;

    @Relationship(type = "ENROLLED", direction = Relationship.OUTGOING)
    private Set<Course> courses = new HashSet<Course>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Course> getCourses() {
        return courses;
    }

    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}
In this code, a new annotation @Relationship is used to define the relationship of Student with Course. The type property of this annotation is a String which indicates the type of the relationship. The direction indicates the direction of the edge.

According to this code, an arrow representing the edge will leave the Student object and points a Course object.


Step 7:
Modify the Main.java as given below:
package com.javahelps.ogmhelloworld;

import java.util.Collections;

import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;

import com.javahelps.ogmhelloworld.entities.Course;
import com.javahelps.ogmhelloworld.entities.Student;

public class Main {

    public static final String NEO4J_URL = "http://localhost:7474";
    public static final String USERNAME = "neo4j";
    public static final String PASSWORD = "admin";

    public static void main(String[] args) {
        // Create SessionFactory. Pass the package name of the entity classes as
        // the argument.
        SessionFactory sessionFactory = new SessionFactory("com.javahelps.ogmhelloworld.entities");

        // Create the session
        Session session = sessionFactory.openSession(NEO4J_URL, USERNAME, PASSWORD);

        // Create few courses
        Course oop = new Course();
        oop.setName("Object Oriented Programming");
        oop.setCredits(2.0f);

        Course algo = new Course();
        algo.setName("Advanced Algorithm");
        algo.setCredits(3.0f);

        Course db = new Course();
        db.setName("Database Internals");
        db.setCredits(3.0f);

        // Create few students
        Student alice = new Student();
        alice.setName("Alice");

        Student bob = new Student();
        bob.setName("Bob");

        Student carol = new Student();
        carol.setName("Carol");

        // Add the courses
        alice.getCourses().add(oop);
        alice.getCourses().add(algo);
        alice.getCourses().add(db);

        bob.getCourses().add(oop);
        bob.getCourses().add(algo);

        carol.getCourses().add(algo);
        carol.getCourses().add(db);

        // Persist the objects. Persisting students persists courses as well.
        session.save(alice);
        session.save(bob);
        session.save(carol);

        // Retrieve Students who enrolled for Advanced Algorithm
        Iterable<Student> students = session.query(Student.class,
                "MATCH (c:Course)<-[:ENROLLED]-(student) WHERE c.name = 'Advanced Algorithm' RETURN student",
                Collections.<String, Object> emptyMap());

        // Print all the Students
        for (Student stu : students) {
            System.out.println(stu.getName());
        }
    }
}
SessionFactory can receive any number of packages which contain the entity classes. SessionFactory.openSession method receives the URL, username and password of your Neo4j database. Session.query method is used to execute the Cypher query to retrieve the list of students who enrolled for Advanced Algorithm course.
For more detail about Cypher query, visit to: Neo4j Manual.

Step 8:
Make sure that the Neo4j is running as a server on http://localhost:7474 and run this application. The application should print Alice, Bob and Carol since all of them are taking the Advanced Algorithm course.

Step 9:
To validate that the data is inserted successfully, visit to the Neo4j dashboard and enter the following command to retrieve the Nodes.
MATCH (n) RETURN n

Find the project @ Git Hub.
Previous
Next Post »

1 comments:

Write comments
Gobinath
AUTHOR
August 6, 2016 at 11:17 AM delete

Hi,
Sorry for the late response. I hope this problem is because of the Neo4j version mismatch. I will update the article for the Neo4j OGM 2 version. If you wanna try yourself, have a look at this [1]

[1] https://github.com/neo4j/neo4j-ogm

Reply
avatar

Contact Form

Name

Email *

Message *