Tutorial Persistent Objects
In this section we'll learn about persistent objects, how to customize them and how to create and save them in DB.
Inspecting and Customizing Persistent Objects
Persistent classes in Cayenne implement a DataObject interface. If you inspect any of the classes generated earlier in this tutorial (e.g. org.example.cayenne.persistent.Artist), you'll see that it extends a class with the name that starts with underscore (org.example.cayenne.persistent.auto._Artist), which in turn extends from org.apache.cayenne.CayenneDataObject. Splitting each persistent class into user-customizable subclass (Xyz) and a generated superclass (_Xyz) is a useful technique to avoid overwriting the custom code when refreshing classes from the mapping model.
Let's for instance add a utility method to the Artist class that sets Artist date of birth, taking a string argument for the date. It will be preserved even if the model changes later:
Now we'll create a bunch of objects and save them to the database. An object is created and registered with ObjectContext using "newObject" method. Objects must be registered with DataContext to be persisted and to allow setting relationships with other objects. Add this code to the "main" method of the Main class:
Note that at this point "picasso" object is only stored in memory and is not saved in the database. Let's continue by adding a Metropolitan Museum "Gallery" object and a few Picasso "Paintings":
Now we can link the objects together, establishing relationships. Note that in each case below relationships are automatically estabslished in both directions (e.g. picasso.addToPaintings(girl) has exactly the same effect as girl.setToArtist(picasso)).
Now lets save all five new objects, in a single method call:
Now you can run the application again as described in the previous section. The new output will show a few actual DB operations:
So first Cayenne creates the needed tables (remember, we used "CreateIfNoSchemaStrategy"). Then it runs a number of inserts, generating primary keys on the fly. Not bad for just a few lines of code.
Next Step: Tutorial SelectQuery