2 Replies Latest reply: Oct 27, 2010 9:46 AM by 698529 RSS

    CMT - getTransaction

    698529
      How can I get the instance of the transaction from a CMT EJB method?
      Something like in BMT: context.getUserTransaction().
      I know I can't change the properties of a CMT transaction, but I would like to display those properties.
      For instance I would like to see the ID of the transaction in order to compare to the IDs shown in the log file.

      Mauro.
        • 1. Re: CMT - getTransaction
          René van Wijk
          You can inject an EjbContext into your session or messagedrivenbean.
          From this context you can call ejbContext.getUserTransaction()

          Note from the Javadocs that you are only allowed to use this
          if your enterprise bean is using bean managed transactions.
          http://download.oracle.com/javaee/5/api/javax/ejb/EJBContext.html#getUserTransaction%28%29

          You can also lookup an instance of UserTransaction, for example,
          Context context = null;
          try {
               context = new InitialContext();
               userTransation = (UserTransaction)context.lookup("java:comp/UserTransaction");
          } catch (NamingException e) {
               e.printStackTrace();
          }
          • 2. Re: CMT - getTransaction
            698529
            Thanks, René.

            The lookup worked fine in a Session Bean (EJB3) with CONTAINER Managed Transaction.


            @Stateless(mappedName = "MyInterface")
            @TransactionAttribute(TransactionAttributeType.REQUIRED)
            public class MyEJB implements MyInterface{
            ....@Resource
            ....SessionContext context;
            ....
            ...public void myMethod() {
            ......ClientTransactionManagerImpl userTransation = (ClientTransactionManagerImpl)context.lookup("java:comp/UserTransaction");
            ......System.out.println("Transaction: " + userTransation.getTransactionKey());
            ....
            ....}
            }