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.
In this example you will see how to change a relationship from a OneToOne type to a OneToMany.
Onyx supports changing any relationship from a To One to a To Many however, changing a To Many to a To One is not supported. The reason for that is because Onyx can not automatically determine which record to associate as the To One relationship due to not having the prior To One constraint. If you need to make a change like that you must use the PersistenceManager.stream API to perform a manual migration.
Define a model including the Payment and Invoice entities.
As you can see the Invoice has a relationship type of RelationshipType.ONE_TO_ONE and the inverse within the Payment also has a relationship type of RelationshipType.ONE_TO_ONE.
This is flawed since it is possible to make multiple payments and apply it to a single invoice.
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
before updating the relationship model of the Invoice and Payment com.onyxdevtools.entities.
Prior to running this script, ensure the database is deleted so that we can
with a clean slate.
If the script runs successfully you have created an Invoice and associated it to a Payment.
The Invoice defines the payment relationship to have a cascadePolicy of CascadePolicy.SAVE.
Run the Main class
Connect to a new database and seed the data.
Take note of the database location as you will need it later to use in another
Modify the Invoice and Payment entities to change the relationship cardinality.
The Invoice to Payment relationship has been changed from a RelationshipType.ONE_TO_ONE to a RelationshipType.MANY_TO_ONE and
the Payment to Invoice relationship has been changed from a RelationshipType.ONE_TO_ONE to a RelationshipType.ONE_TO_MANY.
In this example we are changing the relationship type or cardinality but you do have the ability to change other properties on the relationship including:
Re-Connect to the Database
Create a script to reconnect to the database.
The database location should be the same as what was declared in the first
Verify Updated Relationship
Verify you can associate multiple payments after updating the data model by persisting multiple payments and applying them to the same invoice.
First verify the existing relationship that was a ONE_TO_ONE is still in tact and associated to the entity.
The initialize method is used to hydrate the relationship as opposed to reloading the entire entity.