Java Reference
In-Depth Information
It's important to note that the
EJBContext.getRollbackOnly()
and
setRoll-
backOnly()
methods will throw an
IllegalStateException
if you call them
while in BMT. These methods can only be called while you're in CMT. Next, let's see how
the obtained
UserTransaction
interface is used.
6.3.3. Using user transactions
You've already seen the
UserTransaction
interface's most frequently used methods:
begin
,
commit
, and
rollback
. The
UserTransaction
interface has a few other
useful methods you should take a look at as well. Let's take a look at the entire interface:
public interface UserTransaction {
public void begin() throws NotSupportedException, SystemException;
public void commit() throws RollbackException,
HeuristicMixedException,HeuristicRollbackException, SecurityException,
IllegalStateException, SystemException;
public void rollback() throws IllegalStateException,
SecurityException,SystemException;
public void setRollbackOnly() throws IllegalStateException,
SystemException;
public int getStatus() throws SystemException;
public void setTransactionTimeout(int seconds) throws SystemException;
}
The
begin
method creates a new low-level transaction behind the scenes and associates it
with the current thread. You might be wondering what would happen if you called the
be-
gin
method twice before calling
rollback
or
commit
. Perhaps it's possible to create a
nested transaction using this approach. In reality, the second invocation of
begin
would
throw a
NotSupportedException
because Java EE doesn't support nested transac-
tions. The
commit
and
rollback
methods, on the other hand, remove the transaction
attached to the current thread by the
begin
method. Whereas
commit
sends a “success”
signal to the underlying transaction manager,
rollback
abandons the current transaction.
The
setRollbackOnly
method on this interface might be slightly counterintuitive as
well. After all, why bother marking a transaction as rolled back when you can roll it back
yourself?
To understand why, consider the fact that you could call a CMT method from your BMT
bean that contains a length calculation and checks the transactional flag before proceeding.
Because your BMT transaction would be propagated to the CMT method, it might be pro-