Onyx Database: One to One Relationship Tutorial

You can download the code for this example here:

OnyxDevTools/onyx-database-samples/relationships.

The core features of an Object Relationship Mapping (ORM) Database is to create relationships. The One to One relationship is used to constrain the cardinality to a single object.

  1. Declare an entity with a OneToOne Relationship.

    Below illustrates how to use the @Relationship annotation to define a relationship to a Skipper.

    Notes:
    The relationship type is specified as RelationshipType.ONE_TO_ONE
    The inverseClass attribute is used to define the declared relationship class. This must be the same as the declared relationship property.
    Inverse name property must correspond to the attribute name on the Relationship's declared class.
    Fetch Policy is ignored when declaring a One to One relationship
    Notice the cascadePolicy is CascadePolicy.ALL. This indicates we wish to save or delete the related entity when persisting.
  2. Declare the inverse relationship entity with a One to One Relationship

    Below illustrates how to use the @Relationship annotation to define the inverse entity to the Sailboat.

    Notes:
    The corresponding relationship type is specified as RelationshipType.ONE_TO_ONE
    The relationship type must correspond to the matching parent entity.
  3. Define a Sailboat entity and a Child entity.

    This piece of code will associate the skipper to the sailboat.

    Notes:
    Onyx does not differentiate between a parent or a child entity. In this case the cascade policy determines the behavior of how the entities behave when persisting. Also note that the entities do not have to be "attached" prior to persisting. It is designed for ease of use and simplicity. When using alternative ORMs such as JPA or Hibernate this has been a point of frustration.
  4. Persist the Sailboat entity

    After persisting, Onyx will automatically correlate the sailboat attribute on the skipper entity.

    Notes:
    Since the cascadePolicy is CascadePolicy.ALL the child entity will be automatically persisted.
  5. Fetch the newly created Sailboat entity
    Notes:
    Notice the child entity has been hydrated.
  6. One to Many Relationship