Updating an attribute within your model

You can download the code for this example here:

OnyxDevTools/onyx-database-samples/model-updates/ ... UpdateFieldDemo.java.

There are 2 parts to this example. The first part is to create an existing database containing the original structure of your model. The second is to modify specific parts of the model and observe how the database handles the updates.

This particular change involves adding an attribute, removing an attribute, and changing an attribute type. In all cases the database handles a lightweight migration.

  1. Define a model including Account, Invoice, and Payment entities.

    There are some inherent flaws in the original data model. First, there are some missing fields and the precision of an integer is not scalable enough for a primary key. The primary key should be of type long.

  2. Create a script to seed some test data

    In order to observe how the database reacts to changes we need to create a script to load sample data before updating the model so that we may preserve the format of the entities before updating the model.

    Notes:
    Prior to running this script, ensure the database is deleted so that we can start with a clean slate.
    If the script runs succesfully you have created an Account, a few Invoices and a Payment.
  3. Run the Main class

    Connect to a new database and seed the data.

    Notes:
    Take note of the database location as you will need it later to use in another script.
  4. Modify the Account entity

    The account entity has several changes including added, removed, and changed attributes.

    Changing attribute types is supported if the original type can be converted to the new type. You may not be able to take advantage of the lightweight migration if you were to change the type from a long to an int. Another example would be attempting to convert a String to a numeric value. In either case you will not be able to cast the original value to the new type.

    Notes:
    The accountHolderName attribute was added
    The balanceDue attribute was removed
    The identifier's type has been changed from an int to a long
  5. Re-Connect to the Database

    Create a script to reconnect to the database.

    Notes:
    The database location should be the same as what was declared in the first script.
  6. Verify New Fields

    Retrieve the account using a long rather than int.

    Notes:
    Removing the field balanceDue does not actually orphan the data. It still exists and is accessible through other means. You could still use the stream API within the PersistenceManager to iterate through the entities in a Map format.
    After saving the account, the balance due is no longer stored in the database since it was overwritten in the new format.
  7. Identifier Updates