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 JPA is performed via an EntityManager. 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 an EntityManager, which you do as follows
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Tutorial");
EntityManager em = emf.createEntityManager();
So we created an EntityManagerFactory for our "persistence-unit" called "Tutorial" which we defined above.
Now that the application has an EntityManager it can persist objects. This is performed as follows
Transaction tx = em.getTransaction();
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);
em.persist(inv);
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
Please note that the finally step is important in that it tidies up connections to the datastore and the EntityManager.
Now we want to retrieve some objects from persistent storage, so we will use a "Query".
In our case we want access to all Product objects that have a price below 150.00 and ordering them in ascending order.
Transaction tx = em.getTransaction();
try
{
tx.begin();
Query q = pm.createQuery("SELECT p FROM Product p WHERE p.price < 150.00");
List results = q.getResultList();
Iterator iter = results.iterator();
while (iter.hasNext())
{
Product p = (Product)iter.next();
... (use the retrieved object)
}
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
If you want to delete an object from persistence, you would perform an operation something like
Transaction tx = em.getTransaction();
try
{
tx.begin();
Query q = em.createQuery("DELETE FROM Person p WHERE p.lastName = 'Jones'");
int numberInstancesDeleted = q.executeUpdate();
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
Clearly you can perform a large range of operations on objects. We can’t hope to show all of these here. Any good JPA book will provide many examples.