As you read in the guide for
EntityManagerFactory
, to control the persistence of your objects
you will require at least one
EntityManagerFactory
. Once you have obtained this object you then use
this to obtain an
EntityManager
. An
EntityManager
provides access to the operations for persistence
of your objects. This short guide will demonstrate some of the more common operations.

You obtain an
EntityManager
as follows

EntityManager em = emf.createEntityManager();

In general you will be performing all operations on a
EntityManager
within a transaction, whether your
transactions are controlled by your J2EE container, by a framework such as Spring, or by locally defined transactions.
In the examples below we will omit the transaction demarcation for clarity.

The main thing that you will want to do with the data layer of a JPA-enabled application is persist your objects
into the datastore. As we mentioned earlier, a
EntityManagerFactory
represents the datastore where the
objects will be persisted. So you create a normal Java object in your application, and you then persist this as follows

em.persist(obj);

This will result in the object being persisted into the datastore, though clearly it will not be persistent until
you commit the transaction. The LifecycleState of the object changes from
Transient
to
PersistentClean
(after persist()), to
Hollow
(at commit).

Once you have persisted an object, it has an "identity". This is a unique way of identifying it.
When you specify the persistence for the class you specified an id class so you can create the
identity from that.
So what ? Well the identity can be used to retrieve the object again at some other part in your application.
So you pass the identity into your application, and the user clicks on some button on a web page and that button
corresponds to a particular object identity. You can then go back to your data layer and retrieve the object
as follows

Object obj = em.find(cls, id);

where
cls
is the class of the object you want to find, and
id
is the identity.