|
A Transaction forms a unit of work. The Transaction manages what happens within that unit of work,
and when an error occurs the Transaction can roll back any changes performed. Transactions can be
managed by the users application, or can be managed by a framework (such as Spring), or can be
managed by a J2EE container. These are described below.
See also :-
When using a JPA implementation such as DataNucleus in a J2SE environment, the Transactions
are known as
Locally Managed Transactions
. The users code will manage the transactions
by starting, and commiting the transaction itself. With these transactions with JPA
you would do something like
EntityManager em = emf.getEntityManager();
EntityTransaction tx = em.getTransaction();
try
{
tx.begin();
{users code to persist objects}
tx.commit();
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
}
em.close();
When you use a framework like Spring
you would not need to specify the
tx.begin(), tx.commit(), tx.rollback()
since that would
be done for you. The basic idea with
Locally Managed transactions
is that you are
managing the transaction start and end.
When using a J2EE container you are giving over control of the transactions to the container.
Here you have
Container Managed Transactions
. In terms of your code, you would do like
the previous example
except
that you would OMIT the
tx.begin(), tx.commit(),
tx.rollback()
since the J2EE container will be doing this for you.
DataNucleus also allows specification of the transaction isolation level. This is specified
via the EntityManagerFactory property
datanucleus.transactionIsolation
.
It accepts the standard JDBC values of
-
read-uncommitted (1)
: dirty reads, non-repeatable reads and phantom reads can occur
-
read-committed (2)
: dirty reads are prevented; non-repeatable reads and phantom reads can occur
-
repeatable-read (4)
: dirty reads and non-repeatable reads are prevented; phantom reads can occur
-
serializable (8)
: dirty reads, non-repeatable reads and phantom reads are prevented
The default is
read-committed
. If the datastore doesn't support a particular
isolation level then it will silently be changed to one that is supported (for example
DB4O only supports
read-committed
so will always use that). As an alternative you
can also specify it on a per-transaction basis as follows (using the values in parentheses
above).
org.datanucleus.jpa.EntityTransactionImpl tx =
(org.datanucleus.jpa.EntityTransactionImpl)pm.currentTransaction();
tx.setOption("transaction.isolation", 2);
|
|