8.5. Lifecycle Examples
Prev | Chapter 8. PersistenceManager | Next

## 8.5. Lifecycle Examples

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.setAuthor (new Person ("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 = pmFactory.getPersistenceManager ();
    pm.currentTransaction ().begin ();
    pm.makePersistent (mag);
    pm.currentTransaction ().commit ();

    // or we could continue using the persistence manager...
    pm.close ();

Example 8.2. Updating Objects

    // assume we have an object id for the magazine we want to update
    Object oid = ...;

    // read a magazine; note that in order to read objects outside of
    // transactions you must have the NonTransactionalRead option set
    PersistenceManager pm = pmFactory.getPersistenceManager ();
    Magazine mag = (Magazine) pm.getObjectById (oid, false);
    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.setIssue (23);
    company.setRevenue (1750000D);
    pm.currentTransaction ().commit ();

    // or we could continue using the persistence manager...
    pm.close ();

Example 8.3. Deleting Objects

    // assume we have an object id for the magazine whose articles
    // we want to delete
    Object oid = ...;

    // read a magazine; note that in order to read objects outside of
    // transactions you must have the NonTransactionalRead option set
    PersistenceManager pm = pmFactory.getPersistenceManager ();
    Magazine mag = (Magazine) pm.getObjectById (oid, false);

    // deletes should always be made within transactions
    pm.currentTransaction ().begin ();
    pm.deletePersistentAll (mag.getArticles ());
    pm.currentTransaction ().commit ();

    // or we could continue using the persistence manager...
    pm.close ();

Prev | Up | Next
8.4. Persistence-Capable Lifecycle Management | Home | 8.6. JDO Identity Management