Java Reference
In-Depth Information
to be instantiated directly and must be obtained from the container.
Listing 6.4
used the
simplest way of getting a
UserTransaction
: injecting it through the
@Resource
an-
notation. There are a couple of other ways to do this: using JNDI lookups or through the
EJBContext
.
JNDI lookups
The application server binds the
UserTransaction
to the JNDI name
java:comp/
UserTransaction
. You can look it up directly using JNDI with this code:
Context context = new InitialContext();
UserTransaction userTransaction = (UserTransaction)context.lookup("java:comp/
UserTransaction");
userTransaction.begin();
// Perform transacted tasks.
userTransaction.commit();
This method is typically used outside of EJBs—for example, if you need to use a transac-
tion in a helper or nonmanaged class in the EJB or web tier where dependency injection
isn't supported. If you find yourself in this situation, you might want to consider another
approach. It's much better to have that code in an EJB with greater access to abstractions.
EJBContext
You can also acquire a
UserTransaction
by invoking the
getUserTransaction
method on
EJBContext
. This approach is useful if you're using a
SessionContext
or
MessageDrivenContext
for some other purpose anyway, and a separate injection
to get a transaction instance would clutter the code. Note that you can use the
getUser-
Transaction
method only if you're using BMT. Calling this in a CMT environment will
cause the context to throw an
IllegalStateException
. The following code shows
the
getUserTransaction
method in action:
@Resource
private SessionContext context;
...
UserTransaction userTransaction = context.getUserTransaction();
userTransaction.begin();
// Perform transacted tasks...
userTransaction.commit();