You are on page 1of 12

EJB Transactions

Summary

This article provides an overview of transaction management in the Java 2 Platform


Enterprise Edition (J2EE) and discusses how EJB's uses the transaction system.

And also this document is a short study notes for the people taking the Enterprise
Architect Exams from SUN or IBM. For more information and in-depth study of EJB
transactions please study the book "Enterprise JavaBeans"
by Richard Monson-Haefel.

By Konda Balabbigari

What is a Transaction?

A transaction is a unit of work that made up of one or more tasks. A transaction can
succeed or fail, i.e. a transaction can commit or rollback.

One of the key features of the Enterprise JavaBeans architecture is to support for
distributed transactions. Generally the transaction system ensures that either the
unit of work completes fully or the entire unit of work fully rolled back.

In Enterprise JavaBeans the bean method execution is expressed as task. It is


possible that sometimes an unit of work may consist of single method execution or
multiple method execution.

The EJB architecture supports only flat transactions, a flat transaction cannot have a
child or nested transactions.

Transaction Technologies

• Object Transaction Services (OTS)


• Java Transaction API (JTA)
• Java Transaction Service (JTS)

ACID Properties

Atomic: A transaction must complete fully or rollback. If a transaction commits, all


its changes are committed. If it rollbacks, then all its changes are undone.

Consistent: A transaction always leads to a correct transformation of the system


state by preserving the state invariance. The data won't be in a partially invalid
state.

Isolated: A transaction must execute serially without affected by other transactions,


or otherwise a transaction must be transparent to other transactions.
Durable: The changes done within a completed transaction must be persistent and
should be never lost.

Updating Multiple Databases

As we know one of the key features of EJBs is support for distributed transactions
and EJBs are transactional objects. Enterprise JavaBeans makes it possible for an
application program to update data in multiple databases in a single transaction.

Figure:

Multiple Databases and Multiple EJB Servers

It is also possible with Enterprise JavaBeans to update databases across multiple EJB
servers within the same transaction.

Figure:
Transaction Manager: Manages transactions behind the scenes.

Resource Manager: It manages the transaction for a single resource.

Transaction support under J2EE

Support for transactions is an essential element of the J2EE architecture. The J2EE
platform supports both programmatic and declarative transaction demarcation. The
component provider can use the Java Transaction API to programmatically
demarcate transaction boundaries in the component code. Declarative transaction
demarcation is supported in enterprise beans, where transactions are started and
completed automatically by the enterprise bean's container. In both cases, the
burden of implementing transaction management is on the J2EE platform. The J2EE
server implements the necessary low-level transaction protocols, such as interactions
between transaction manager and JDBC database systems, transaction context
propagation, and optionally distributed two-phase commit. Currently, the J2EE
platform only supports flat transactions. A flat transaction cannot have any child
(nested) transactions.

Transaction Demarcation

The Enterprise JavaBeans model offers a verity of ways to make use of transactional
services. Transaction demarcation determines who is responsible for starting,
stopping and completing a transaction.

• Client demarcation
• Container demarcation
• Bean demarcation

Client demarcation
A client demarcation is an explicit transaction management. The Java client program
uses javax.transaction.UserTransaction interface to explicitly demarcate transaction
boundaries. The use of client demarcated transactions are not recommended
because, more code, maintenance is required, they may create the possibility of long
running transactions.

How to obtain UserTransaction in EJB 1.0

Generally most of the vendors specify the access to UserTransaction object from the
client program through JNDI API. Here is the small code sample to obtain
UserTransaction object:

Example

InitialContext jndiCtx = new InitialContext();


UserTransaction userTx =
(UserTransaction)jndiCtx.lookup("javax.transaction.UserTransaction");

How to obtain UserTransaction in EJB 1.1

The J2EE specification specifies access UserTransaction object from the client
program through JNDI API. Here is the small code sample to obtain UserTransaction
object:

Example

InitialContext jndiCtx = new InitialContext();


UserTransaction userTx =
(UserTransaction)jndiCtx.lookup("java:comp/UserTransaction");

Container demarcation

The container demarcation is available for both entity and session beans. The
container demarcation uses declarative transaction demarcation where they specify a
transaction attribute during the deployment and the container handles the
transaction demarcation automatically.

The deployer or the application assembler uses the deployment descriptor to specify
the required transaction attributes, then the container support all other issues
regarding transaction demarcation.

The container demarcation is recommended because it reduces code, maintenance


and offers more flexibility in terms of changing the transaction attributes in the
deployment descriptor.

Transactional Specifiers
For the container managed transactions, a bean indicates it's requirements through
two attributes.

• Transaction attributes (determines if and how transactions are needed.)


• Transaction isolation attributes (determines how transactional reads are
isolated)

List of Transaction attributes

Transaction attribute EJB 1.0 (constant) EJB 1.1 (text value)


Not Supported TX_NOT_SUPPORTED NotSupported
Supports TX_SUPPORTS Supports
Required TX_REQUIRED Required
Requires New TX_REQUIRES_NEW RequiresNew
Mandatory TX_MANDATORY Mandatory
Never(EJB 1.1) xxxxx Never
Bean Managed(EJB 1.0) TX_BEAN_MANAGED xxxxx

Generally EJB servers manage transactions implicitly based on the transaction


attributes of the bean. The transaction attributes can be set at bean deployment
time, the attributes can be set for:

• an EJB method
• an entire EJB

If you set the transaction attributes to a bean then the same attributes applies to all
methods. The following example explain how to set the transaction attributes in EJB
1.1.

Example EJB 1.1

<ejb-jar>
....
<assembly-descriptor>
...
<container-transaction>
<method>
<ejb-name>statelessSession</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>

<container-transaction>
<method>
<ejb-name>statelessSession</ejb-name>
<method-name>setName</method-name>
</method>
<trans-attribute>Mandatory</trans-attribute>
</container-transaction>
....
</assembly-descriptor>
....
</ejb-jar>

NotSupported(TX_NOT_SUPPORTED)

If the transaction attribute set as "NotSupported" then the container invokes the
bean method with what is known as unspecified transaction context.

• If the client calls with the transaction context, then the client transaction
context is suspended until bean's business method completes.
• Once the business method execution is completed, then the client transaction
context is resumed.

Supports (TX_SUPPORTS)

• If the client calls with the transaction context, then the client transaction
context is propagated to the bean.
• If the client calls without transaction context, then the client transaction
context is not propagated to bean, then the bean method is executed under
what is known as unspecified context.

Required (TX_REQUIRED)

• If the client calls with the transaction context, then the client transaction
context is propagated to the bean.
• If the client calls without transaction context, then the container starts a new
transaction.

RequiresNew (TX_REQUIRES_NEW)

• If the client calls with the transaction context, then the client transaction
context is suspended for the duration of bean method execution, and the
container starts a new transaction.
• If the client calls without transaction context, then the container starts a new
transaction.
• For all the cases if you set this attribute the container always starts a new
transaction.

Mandatory (TX_MANDATORY)

The Container must invoke an enterprise bean method whose transaction attribute is
set to Mandatory in a client's transaction context.
• If the client calls with the transaction context, then the client transaction
context is propagated to the bean.
• If the client calls without transaction context, then the container throws
javax.transaction.TransactionRequiredException.

Never (EJB 1.1 only)

With this attribute set, the client always required to call the bean without transaction
context.

• If the client calls with the transaction context, then the Container throws
java.rmi.RemoteException.
• If the client calls without transaction context, then the container invokes the
bean method with what is known as unspecified transaction context.

Bean Managed(EJB 1.0 only) (TX_BEAN_MANAGED)

The attribute indicates that the bean itself manages starting the transation or the
stopping the transaction instead of container.

• In EJB 1.0 both entity and session beans support bean managed transactions,
whereas in EJB 1.1 only session beans support bean managed transactions.
• This attribute applies to the entire bean, and cannot be specified for individual
methods.
• If one method is set as bean managed then all the methods must be bean
managed.
• If a bean managed bean is invoked from a transactional client the client's
transaction is suspended and the bean executes its own transaction.
• If a bean managed bean is invoked from a non transactional client then the
bean executes its own transaction.

Summary of Transaction attributes

Transaction Client transaction


Bean transaction context
attribute context
No TX No TX
Not Supported
Client TX No TX
No TX No TX
Supports
Client TX Client TX
No TX New TX
Required
Client TX Client TX
No TX New TX
Requires New
Client TX New TX
Error
No TX
Mandatory (TransactionRequiredException)
Client TX Client TX
Never(EJB 1.1) No TX No TX
Client TX Error (RemoteException)

Bean Managed(EJB No TX New TX


1.0) Client TX New TX

Transaction isolation conditions

The Transaction isolation attribute determine how transactional reads are isolated
and also tells the container to limit the concurrent reads in a database.

These are the following transaction isolation conditions:

• Dirty reads
• Non Repeatable reads
• Phantom reads

Dirty reads

T1 --> Transaction 1
T2 --> Transaction 2

A dirty read can occur if T1 reads the data that has been modified by T2 before
commits (uncommitted). If T2 rolls back, the data read by T1 is invalid because the
rollback undoes the changes.

Non Repeatable reads

Repeatable read guarantees the data read again and again within a same
transaction. A non repeatable occur if T1 reads data and then T2 updates data, if T1
reads data again then T1 will have different results within a same transaction.

Phantom reads

Phantom reads can occur in the following situations:


T1 reads the set of records that match some criteria
T2 inserts new records that match some criteria
T1 reads again set of records which now includes new inserted records that were not
part of the original matching criteria.

Transaction isolation level attributes

The Transaction isolation attribute determine how transactional reads are isolated
and also tells the container to limit the concurrent reads in a database.

List of EJB 1.0 Transaction isolation level attributes

Transaction isolation level ControlDescriptor constant


Read Uncommitted TRANSACTION_READ_UNCOMMITTED
Read Committed TRANSACTION_READ_COMMITTED
Repeatable Read TRANSACTION_REPEATABLE_READ
Serializable TRANSACTION_SERIALIZABLE

In EJB 1.1 the isolation levels are not controlled through(ControlDescriptor)


declarative attributes like in EJB 1.0. In EJB 1.1 the deployer sets the isolation level
for container managed transactions and for bean managed transactions the bean
developer sets the isolation levels.

Read Uncommitted (TRANSACTION_READ_UNCOMMITTED)

If you set this isolation level the transaction can read uncommitted data. This
permits Dirty reads, nonrepeatable reads and phantom reads.

Read Committed (TRANSACTION_READ_COMMITTED)

If you set this isolation level the transaction cannot read uncommitted data. This
forbids dirty reads and permits nonrepeatable reads and phantom reads.

Repeatable Read (TRANSACTION_REPEATABLE_READ)

If you set this isolation level the transaction cannot change the data that is being
read by a different transaction. This forbids dirty reads, nonrepeatable reads and
permits phantom reads.

Serializable (TRANSACTION_SERIALIZABLE)

If you set this isolation level the transaction cannot read, write the data that is being
read by a different transaction. This forbids dirty reads, nonrepeatable reads and
phantom reads.

NOTE: All the methods invoked within a same transaction must have same isolation
level. You cannot mix the isolation levels.

Bean demarcation

The bean managed demarcation is similar to client managed demarcation, uses


javax.transaction.UserTransaction interface. In EJB 1.0 both entity and session beans
can use the bean managed demarcation where as in EJB 1.1 only session beans can
use the bean managed demarcation.

In EJB 1.1 only session beans with <transaction-type>Bean</transaction-type> can


be bean-managed transaction beans.

In EJB 1.0 beans (entity and session) with transaction attribute TX_BEAN_MANAGED
can be bean-managed transaction beans.

The beans to manage its own transaction, a bean needs to obtain the
UserTransaction object using EJBContext interface and under environment entry
java:comp/UserTransaction. Here is the small code sample to obtain UserTransaction
object using EJBContext object:

Example

SessionContext ejbContext;
UserTransaction userTx = ejbContext.getUserTransaction();
userTx.begin();

// Do some work

userTx.commit();

In EJB 1.1 getting the UserTransaction object either from EJBContext or from JNDI
ENC are same. Here is the small code sample to obtain UserTransaction object using
JNDI ENC object:

Example

InitialContext jndiCtx = new InitialContext();


UserTransaction userTx =
(UserTransaction)jndiCtx.lookup("java:comp/env/UserTransaction");

EJBContext rollback methods

An enterprise bean with bean-managed transaction demarcation must not use the
following methods of the EJBContext object.

• getRollbackOnly()
• setRollbackOnly()

An enterprise bean with bean-managed transaction demarcation must use


getStatus() and rollback() methods of UserTransaction object.

EJB Exception Handling

There are two categories of exception we may see when we are developing EJB
applications.

• Application Exceptions
• System Exceptions

Application Exceptions

If there is an application exception the transactions are not rolled back automatically.
The bean provider is responsible for throwing application exceptions from the
business method to report business logic exception to the client.
The application exception must not be defined as a subclass of the
java.rmi.RemoteException or of the java.lang.RuntimeException. These are the
standard EJB application exceptions from javax.ejb package.

• CreateException
• DuplicateKeyException
• FinderException
• ObjectNotFoundException
• RemoveException

All the above mentioned standard EJB exceptions are to report errors to client from
the create, remove, and finder methods. The following section explains details of all
above mentioned exceptions.

CreateException

From the client's perspective, a CreateException or the subclass of CreateException


indicates that an application level error occurred during the create() operation. The
bean provider throws the CreateException from ejbCreate() and ejbPostCreate()
methods to indicate an application level error from the create operation.

The container may or may not roll back the transaction when this exception occurs.

DuplicateKeyException

The DuplicateKeyException is a subclass of CreateException. This exception is thrown


by the ejbCreate() methods to indicate that the entity object cannot be created
because an entity object is already exists with same key.

The bean provider should not mark the transaction for rollback before throwing this
exception.

FinderException

From the client's perspective, a FinderException or the subclass of FinderException


indicates that an application level error occurred during the find() operation. The
bean provider throws the FinderException from ejbFind<xxx>() methods to indicate
an application level error from the finder method.

The bean provider should not mark the transaction for rollback before throwing this
exception.

ObjectNotFoundException

The ObjectNotFoundException is a subclass of FinderException. This exception is


thrown by the ejbFind<xxx>() methods to indicate that the requested entity object
does not exist.
Only single-entity finder methods should throw this exception. Multi entity finder
methods should not throw this exception. Multi-object finders should return empty
collection if no matching objects were found.

RemoveException

From the client's perspective, a RemoveException or the subclass of


RemoveException indicates that an application level error occurred during the
remove() operation. The bean provider throws the RemoveException from
ejbRemove() methods to indicate an application level error from the remove
method.

The container may or may not roll back the transaction when this exception occurs.

System Exceptions

The system exceptions are RemoteException, RuntimeException and their


subclasses. The bean instance may encounter system exceptions during the
execution of a business method or container callback method. The EJBException is a
subclass of RuntimeException, it is considered to be system exception and does not
have to be listed in the throws clauses of the business methods.

If there is a system exception the container always:

• Roll back the current transaction


• Log the exception
• Discard the bean instance.
• Throw the RemoteException

For example NoSuchObjectException is thrown when the stateful bean instances are
discarded, subsequent invocations of the bean's methods by the client, in the case of
entity beans it throws as javax.ejb.NoSuchEntityObject. The NoSuchObjectException
is a subclass of RemoteException. The example of RuntimeException are
NullPointerException and IndexOutOfBoundsException.

If the client started the transaction and propagated to the bean, if there is a system
exception then the javax.transaction.TransactionRolledbackException is thrown to
the client by the container, in all other cases the system exception is thrown as
RemoteException.

You might also like