Neo4j-OGM Documentation
repository·master·Indexed 18 days ago
https://github.com/neo4j/neo4j-ogmA fast object-graph mapping library for Neo4j that maps POJO domain objects to a graph database using annotations. It supports DTO mapping, custom transaction managers, and dynamic class registration via DomainInfo. The library provides different version lines for Neo4j 3.5, 4.4, and 5.x, with version 5.0.x requiring the Neo4j Java driver 6 series.
What's inside Neo4j-OGM
- Neo4j-OGM is a high-performance object-graph mapping (OGM) library designed for Neo4j. It allows developers to map simple POJO (Plain Old Java Object) domain models to a Neo4j graph database using annotations, similar to how JPA works for relational databases. It is optimized for server-based installations using Cypher and focuses on performance through features like non-reflection based classpath scanning, variable-depth persistence, smart object-mapping, and user-definable session lifetimes.
Neo4j-OGM Framework Integrations
masterNeo4j-OGM provides official integrations for popular frameworks:
- Quarkus: The Neo4j-OGM Quarkus Extension is optimized for Quarkus' build-time approach.
- Spring: The Neo4j-OGM Spring Data fork provides continued support for Spring Data Neo4j 5 for modern Spring versions.
What is Neo4j-OGM and how does it work?
masterNeo4j-OGM (Object-Graph Mapper) is a pure Java library designed to map domain models to a Neo4j graph database. It allows you to persist annotated domain objects by mapping object instances to nodes and object references to relationships (or serialized properties).
Key features include:
- Abstraction: Provides a way to persist and query domain models without using low-level drivers directly.
- Cypher Integration: Uses Cypher statements for database operations, while allowing developers to supply custom queries when generated ones are insufficient.
- Change Tracking: Minimizes necessary updates by tracking changes to objects.
- Transitive Persistence: Handles reading and updating the neighborhoods of an object.
- Transport Layer: Connects to Neo4j via the Bolt protocol using the Neo4j Java Driver.
Behavior of events for connected objects and collections
masterThe event mechanism covers the entire reach of the domain model during a persistence operation:
- Connected Objects: If you save a top-level object, events are fired for all reachable connected objects in the domain model, even if they weren't explicitly passed to the
save()method. - Collections: When saving or deleting a collection, separate events are fired for each individual object in that collection, rather than a single event for the collection itself.
- Type Deletion: When deleting a class type (e.g.,
session.delete(Document.class)),PRE_DELETEandPOST_DELETEevents are raised for the type itself, not for individual instances (as the instances may not be known to the OGM). - Uniqueness: The mechanism guarantees that no more than one event of the same type is fired for a single object within a single request, even if multiple changes affect that object.
- Connected Objects: If you save a top-level object, events are fired for all reachable connected objects in the domain model, even if they weren't explicitly passed to the
How the Neo4j-OGM Session works
masterThe
Sessionis the core driver of the object-graph mapping framework. It manages the lifecycle of entities by tracking changes (dirty tracking) to ensure only modified entities and relationships are persisted, which optimizes performance for large graphs.Key Behaviors:
- Caching: Once an entity is loaded, subsequent loads within the same session return the cached instance. The subgraph expands if new relationships are retrieved.
- Scope: The session should ideally correspond to a single "unit of work".
- Long-running sessions: Risk working with outdated data from other users.
- Short-lived sessions: May result in more expensive save operations if the session isn't aware of previously loaded objects.
- Refreshing Data: To fetch fresh data, use a new session or call
Session.clear(). Note thatSession.clear()wipes the entire cache and disables dirty tracking for operations following the call.
Requirement: No-Args Constructor
masterNeo4j-OGM requires all annotated entities (Nodes and Relationship Entities) to have a public no-args constructor. This is necessary for the OGM to instantiate the objects when mapping data from the graph back into Java objects.Understand the relationship between Neo4j-OGM and Spring Data Neo4j (SDN)
masterNeo4j-OGM is the underlying Object-Graph Mapper that provides much of the core functionality for Spring Data Neo4j (SDN) in older versions.
- SDN up to version 5.3.x: Uses Neo4j-OGM under the hood (similar to how Spring Data JPA uses Hibernate).
- SDN 6.x (Spring Boot 2.4) and later: Does not require Neo4j-OGM.
Important Compatibility Note: Neo4j-OGM 4+ is not a drop-in replacement for Spring Data 5.x.
Use Filters to customize Cypher WHERE clauses
masterFilters allow you to customize the
WHEREclause of the Cypher queries generated by Neo4j-OGM. AFilteris composed of a property name, aComparisonOperator, and a value. By default, filters use aPropertyComparisonfunction, but you can provide a customFilterFunctionduring instantiation.Important: Filters are immutable. You cannot change filter values after they have been instantiated.
// Basic usage to load all entities of a class matching a specific property condition Collection<Satellite> satellites = session.loadAll(Satellite.class, new Filter("manned", ComparisonOperator.EQUALS, true));Manage database schema without Auto Index Manager
masterThe
Auto Index Manager, which previously handled the automatic creation of indexes and constraints, has been removed in Neo4j-OGM 4.To manage your schema (indexes, constraints, etc.), you should now use dedicated schema management tools. Recommended alternatives include:
- Neo4j-Migrations: https://michael-simons.github.io/neo4j-migrations/
- Liquibase: Using the Neo4j-Plugin for Neo4j.
Note for Migrating Codebases: While the functionality is removed, the existing interfaces remain available to prevent immediate refactoring needs and to support the
Neo4j-Migrationsannotation processor during your transition.Use relationship entities to model properties on relationships
masterIn Neo4j OGM, if a relationship between two nodes needs to store data (e.g., the
rolesan actor played or theratinga reviewer gave), you cannot use a simple collection of nodes. Instead, you must implement a relationship entity.A relationship entity is a class that:
- Contains the properties specific to the relationship.
- Holds references to the two nodes involved in the relationship (e.g.,
Movie movieandPerson person).
Transport mode changes in Neo4j-OGM 4
masterNeo4j-OGM 4 has removed support for certain transport modes to align with modern Neo4j standards:
- HTTP Transport: Removed. Users should use the Bolt protocol, which provides a more robust feature set.
- Embedded Transport: Deprecated/Removed. As the baseline for supported databases is now Neo4j 5.x, embedded transport support is no longer provided.
Use @Id and @GeneratedValue instead of @GraphId
masterThe
@GraphIdannotation is deprecated. To manage entity identity, use aLongfield annotated with both@Idand@GeneratedValueinstead.@Id @GeneratedValue private Long id;