Persistent classes in Cayenne implement a DataObject interface. If you inspect any of classes generated earlier in this tutorial (e.g. cayenne.tutorial.Artist), you'll see that it extends a class with the name that starts with underscore (cayenne.tutorial.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 of the custom code when refreshing classes from the mapping model.
Let's add a utility method to the Artist class that sets Artist date of birth, taking a string argument for the date:
We'll continue by creating a bunch of new objects and saving them to the database.
An object is created and registered with DataContext using "newObject" method. (Note that objects must be registered with DataContext to be persisted and to allow relationships with other objects.) Add this code to the "main" method:
Note that at this point "picasso" object is only stored in memory and is not saved in teh 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:
Now you can run the application again as described here. The new output will look like this:
The first few SELECT's are done by Cayenne primary key generator (note that we did not assign any explicit PKs to the objects - Cayenne does this automatically). Following them are the statements generated to save the objects that we created.
Next Step: Tutorial Mapping Query