4.4. InstanceCallbacks

Your persistent classes can implement the javax.jdo.InstanceCallbacks interface to receive callbacks when certain JDO lifecycle events take place. This interface consists of four methods:

Unlike the PersistenceCapable interface, you must implement the InstanceCallbacks interface explicitly if you want to receive lifecycle callbacks.

Example 4.3. Using the InstanceCallbacks Interface

/**
 * Example demonstrating the use of the InstanceCallbacks interface to
 * persist a java.net.InetAddress and implement a privately-owned relation.
 */
public class Host
    implements InstanceCallbacks
{
    // the InetAddress field cannot be persisted directly by JDO, so we
    // use the jdoPostLoad and jdoPreStore methods below to persist it
    // indirectly through its host name string
    private transient InetAddress address;    // non-persistent
    private String                hostName;   // persistent

    // set of devices attached to this host
    private Set devices = new HashSet ();

    // setters, getters, and business logic omitted

    public void jdoPostLoad ()
    {
        // form the InetAddress using the persistent host name
        try
        {
            address = InetAddress.getByName (hostName);
        }
        catch (IOException ioe)
        {
            throw new JDOException ("Invalid host name: " + hostName, ioe);
        }
    }

    public void jdoPreStore ()
    {
        // store the host name information based on the InetAddress values
        hostName = address.getHostName ();
    }

    public void jdoPreDelete ()
    {
        // delete all related devices when this host is deleted
        JDOHelper.getPersistenceManager (this).deletePersistentAll (devices);
    }

    public void jdoPreClear ()
    {
    }
}