Onyx Database: One to Many Relationship Tutorial

You can download the code for this example here:

OnyxDevTools/onyx-database-samples/relationships.

The One to Many relationship is a powerful methodology for associating several child entities to a parent. Onyx allows features such as Lazy Loading and customized transactions.

  1. Declare an entity with a One To Many relationship to crew members.

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

    Notes:
    The relationship type is specified as RelationshipType.ONE_TO_MANY
    The declared property must implement a List interface for To Many relationships.
    The inverseClass attribute is used to define the declared relationship class. It is often helpful to set the List Generic to the inverse class type
    Inverse name property must correspond to the attribute name on the Relationship's declared class.
    Fetch Policy is used to determine whether you want the entire set of relationships loaded or just references. If you set it to FetchPolicy.LAZY the relationship's List implementation will be a LazyRelationshipCollection. The LazyRelationshipCollection is used to lazily load references and hydrate entities whenever referencing it using the List interface.
    Notice the cascadePolicy is CascadePolicy.ALL. This indicates we wish to save the relationships within the list upon persisting the parent entity. Upon persisint an entity with a relationship object removed from the relationship list, it will remove the relationship reference and not actually delete the related entity.
  2. Declare the inverse relationship entity with a Many to One Relationship

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

    Notes:
    The corresponding relationship type is specified as RelationshipType.MANY_TO_ONE
    The relationship type must correspond to the matching parent entity.
  3. Define a Sailboat entity and its Crew Members Instantiate a sailboat and the relationship List. Also create several crew members and add the relationship list.
    Notes:
    Associate the list of crew members to the Sailboat
  4. Persist the Sailboat entity
    Notes:
    Since the cascadePolicy is CascadePolicy.ALL the crew member entities will be automatically persisted.
    After persisting, Onyx will automatically correlate the sailboat attribute to the crew members.
  5. Fetch the Sailboat entity
    Notes:
    Notice the crew member list has been loaded and is a LazyRelationshipCollection. Upon referencing the element in the List that crew member will be hydrated.
  6. Many to Many Relationship