Onyx Database: Fetch Policy Tutorial

The Fetch Policy can be used to optimize your object graph. Onyx enables developers to load only what they need. There are instances when users would like to reduce the size of the object graph in order to save memory and network overhead by lazily or not loading relationships.

Policy Description

FetchPolicy.EAGER

Eager fetch policy will hydrate the entire relationship and all of the subsequent object graph.

FetchPolicy.LAZY

Lazy fetch policy will return references to the relationship data. When referenced using the List interface, the relationship will be lazily filled in.

FetchPolicy.NONE

The relationship will not be populated upon fetching an entity. It will sometimes be populated in the event the entity is already cached.

You can download the code for this example here:

OnyxDevTools/onyx-database-samples/relationships.

  1. Define your ORM Object Graph including Series, Season, Episode and Actor
    Notes:
    Notice the Series.seasons relationship has a fetch policy of FetchPolicy.EAGER
    Notice the Season.episodes relationship has a fetch policy of FetchPolicy.LAZY
    Lastly the Episode.actors relationship has a fetch policy of FetchPolicy.NONE
  2. Populate test data including all objects in your object graph including Series, Seasons, Episodes, and Actors.

    For this example all of the relationships have CascadePolicy of CascadePolicy.SAVE or CascadePolicy.ALL. This is to ensure the entire object graph is persisted.

    Notes:
    At the end of the code block we persist the series entity using manager.saveEntity
  3. Get a clean copy of the Season you just created and verify the eager relationship.
    Notes:
    We are re-fetching it in order to see how the relationships are populated from the database.
    Verify the seasons are loaded and contain expected seasons that we created.
  4. Verify the episodes are lazily loaded.
    Notes:
    The season.episodes relationship should be an instance of LazyRelationshipCollection.
    Upon referencing the List the episode should be hydrated.
    Notice in this object graph the Episode.actors relationship has a fetch policy of FetchPolicy.NONE. This will not guarantee that the relationship will be null. If the episode entity is cached, the collection will be populated otherwise, it will be null.

    Onyx maintains an elastic cache and does not guarantee items in memory. If you need to reference that relationship, you should use manager.initialize(episode, "actors") to hydrate the relationship.

  5. Indexing