Home

EntityTransaction

EntityTransaction is an API element of the Java Persistence API (JPA) that provides programmatic control over resource-local transactions for a specific EntityManager. It is used when an application manages transactions directly rather than through container-managed transactions (JTA). An EntityManager exposes its transaction via getTransaction(), and the returned EntityTransaction governs the current persistence context for that manager.

Typical usage involves obtaining the transaction, beginning it, performing data operations, and then committing or rolling

The EntityTransaction interface provides the following methods:

- begin(): starts a new transaction. Throws IllegalStateException if a transaction is already active.

- commit(): commits the current transaction. Throws IllegalStateException if no transaction is active and may throw persistence-related

- rollback(): rolls back the current transaction. Throws IllegalStateException if no transaction is active.

- setRollbackOnly(): marks the current transaction so that a subsequent commit will result in a rollback.

- boolean getRollbackOnly(): returns true if the transaction has been marked for rollback.

- boolean isActive(): returns true if a transaction is currently active.

Behavior and considerations: Resource-local transactions controlled by EntityTransaction are tied to a single EntityManager and are

See also: Java Persistence API (JPA), EntityManager, JTA, PersistenceException.

back
as
needed.
For
example:
EntityTransaction
tx
=
em.getTransaction();
try
{
tx.begin();
em.persist(entity);
//
other
writes
tx.commit();
}
catch
(Exception
ex)
{
if
(tx.isActive())
{
tx.rollback();
}
}
exceptions
if
the
commit
fails.
distinct
from
JTA
transactions.
They
are
suitable
in
non-container
environments
or
when
using
non-JTA
data
sources.
Some
environments
or
providers
may
impose
restrictions,
and
mixing
resource-local
with
container-managed
transactions
is
inappropriate.
In
container
environments,
JTA
is
typically
preferred
for
coordinated
transactions
across
multiple
resources.