Onyx Database: Many to Many Relationship Tutorial

You can download the code for this example here:

OnyxDevTools/onyx-database-samples/relationships.

The Many to Many relationship is used for defining non-constrained associations.

  1. Declare a Movie entity with a ManyToMany Relationship.

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

    Notes:
    The relationship type is specified as RelationshipType.MANY_TO_MANY
    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.
    The inverse property must correlate to a Many to Many relationship
    Notice the cascadePolicy is CascadePolicy.SAVE. This indicates we wish to save all of the entities within the list. For optimal performance you may not want to cascade save. If that is not the case you must ensure the relational entities must exist prior to specifying them in the to many relationship or risk not persisting the relationship.
    The actors relationship is defined as a List. This is to maintain an ordered list rather than un-ordered collection.
  2. Define an Actor entity as it relates to movies.
    Notes:
    Using this example an actor can take part in multiple movies. Likewise, a movie has several actors.
    For optimal performance, it may not make sense to set the cascadePolicy to ALL or SAVE for both the Actor and Movie com.onyxdevtools.entities. Design the cascade policy to conform to your persistence logic.
  3. Persist the Movie entity
    Notes:
    Since the cascadePolicy is CascadePolicy.SAVE the actor entity will be automatically persisted.
    After persisting, Onyx will automatically correlate the movie entity to the actors' movie list.
    One thing to note is that Harrison Ford is defined in both the movies' actor lists. Onyx differs from some ORMs that require the entity to be refreshed after persisting the first movie. Onyx is intuitive enough to gather that the actor entity has already been persisted and will be be associated rather than causing an error.
    Defining the inverse relationship values are optional. Again, Onyx is intuitive enough that it knows what you are trying to achieve here.
  4. Find and Hydrate the Actor entity
    Notes:
    Initialize is used to hydrate a lazy relationship, "movies."
    Notice the actor entity has been hydrated and the movies have been associated to the actor.
  5. Cascade Policy