Writing your own classes to be persisted is the start point, but you now need to define which objects of these classes are actually persisted, and when.
Interaction with the persistence framework of JDO is performed via a PersistenceManager.
This provides methods for persisting of objects, removal of objects, querying for persisted objects, etc.
This section gives examples of typical scenarios encountered in an application.
The initial step is to obtain access to a PersistenceManager, which you do as follows
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("Tutorial");
PersistenceManager pm = pmf.getPersistenceManager();
Now that the application has a PersistenceManager it can persist objects.
This is performed as follows
Transaction tx=pm.currentTransaction();
try
{
tx.begin();
Inventory inv = new Inventory("My Inventory");
Product product = new Product("Sony Discman", "A standard discman from Sony", 49.99);
inv.getProducts().add(product);
pm.makePersistent(inv);
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
-
We have persisted the Inventory but since this referenced the Product then that is also persisted.
-
The finally step is important to tidy up any connection to the datastore, and close the PersistenceManager
If you want to retrieve an object from persistent storage, something like this will give what you need.
This uses a "Query", and retrieves all Product objects that have a price below 150.00, ordering them in ascending price order.
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price < 150.00 ORDER BY price ASC");
List<Product> products = q.executeList();
Iterator<Product> iter = products.iterator();
while (iter.hasNext())
{
Product p = iter.next();
... (use the retrieved objects)
}
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
If you want to delete an object from persistence, you would perform an operation something like
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
... (retrieval of objects etc)
pm.deletePersistent(product);
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
Clearly you can perform a large range of operations on objects.
We can’t hope to show all of these here. Any good JDO book will provide many examples.