Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing transaction status in container managed beans

I have a @Stateless EJB using container managed transaction. Is there a way to access the "status" of javax.transaction.UserTransaction? That is, calling UserTransaction.getStatus() inside the bean methods?

I know access to UserTransaction is prohibited in container managed beans, but I would like to know, is there any other way to get access to getStatus() method?

like image 530
Vicky Avatar asked Jun 05 '11 03:06

Vicky


2 Answers

If you only need to know if the transaction is marked for rollback, then use EJBContext.getRollbackOnly. Otherwise, with JTA 1.1, you can use TransactionSynchronizationRegistry:

TransactionSynchronizationRegistry tsr = (TransactionSynchronizationRegistry)
  new InitialContext().lookup("java:comp/TransactionSynchronizationRegistry");
int status = tsr.getTransactionStatus()
like image 51
Brett Kail Avatar answered Nov 17 '22 18:11

Brett Kail


I don't think you've understood the responsibility of the UserTransaction class. It does not exist to provide you with access to the current running transaction. It is used to initiate any communication with the Transaction Manager of the container, especially for beginning and ending bean-managed transactions; that is why you must not access it from a container managed transaction context.

I would like to know, is there any other way to get access to getStatus() method?

No, one cannot, atleast not using the EJB APIs. One can at most, use EJB interceptors to log the fact that EJB methods have been invoked. You'll need to be quite intelligent to track state across calls, and then infer the transaction state.

If you are not averse to use Container specific APIs, you might be able to access the underlying transaction. Be forewarned, for the approach listed below might not work if you do not know how to use it, or if the container prohibits you from doing so. The mechanism described below is how the SpringFramework gains access to the JTA transaction manager and is able to create and manage transactions.

In the case of Oracle WebLogic, one can obtain a reference to the TranactionHelper class, which can be used to obtain a reference to the current transaction associated with the thread, whose status can be obtained. I would point to the sources of the Transaction SPI for JTA in the Spring framework, if you need to pursue this course for other application servers.

like image 2
Vineet Reynolds Avatar answered Nov 17 '22 16:11

Vineet Reynolds