Example 8.1. Persisting Objects
// create some objects
Magazine mag = new Magazine ("1B78-YU9L", "JavaWorld");
Company pub = new Company ("Weston House");
pub.setRevenue (1750000D);
mag.setPublisher (pub);
pub.addMagazine (mag);
Article art = new Article ("JDO Rules!", "Transparent Object Persistence");
art.addAuthor (new Author ("Fred", "Hoyle"));
mag.addArticle (art);
// we only need to make the root object persistent; JDO will traverse
// the object graph and make all related objects persistent too
PersistenceManager pm = pmf.getPersistenceManager ();
pm.currentTransaction ().begin ();
pm.makePersistent (mag);
pm.currentTransaction ().commit ();
// or we could continue using the PersistenceManager...
pm.close ();
Example 8.2. Updating Objects
Magazine.MagazineId mi = new Magazine.MagazineId (); mi.isbn = "1B78-YU9L"; mi.title = "JavaWorld"; // read a magazine; note that in order to read objects outside of // transactions you must have the NonTransactionalRead option set PersistenceManager pm = pmf.getPersistenceManager (); Magazine mag = (Magazine) pm.getObjectById (mi, true); Company pub = mag.getPublisher (); // updates should always be made within transactions; note that // there is no code explicitly linking the magazine or company // with the transaction; JDO automatically tracks all changes pm.currentTransaction ().begin (); mag.setPrice (5.99); pub.setRevenue (1750000D); pm.currentTransaction ().commit (); // or we could continue using the PersistenceManager... pm.close ();
Example 8.3. Deleting Objects
// assume we have an object id for the company whose subscriptions // we want to delete Object oid = ...; // read a company; note that in order to read objects outside of // transactions you must have the NonTransactionalRead option set PersistenceManager pm = pmf.getPersistenceManager (); Company pub = (Company) pm.getObjectById (oid, true); // deletes should always be made within transactions pm.currentTransaction ().begin (); pm.deletePersistentAll (pub.getSubscriptions ()); pub.getSubscriptions ().clear (); pm.currentTransaction ().commit (); // or we could continue using the PersistenceManager... pm.close ();