Use bean-managed transactions

This topic describes how to enable a session bean or servlet to use bean-managed transactions, to manage its own transactions directly instead of letting the container manage the transactions.

Note that Entity beans cannot manage transactions (so cannot use bean-managed transactions).

To enable a session bean or servlet to use bean-managed transactions, complete the following steps...

  1. Set the Transaction type attribute in the component's deployment descriptor to Bean, as described in Configuring transactional deployment attributes using the Assembly Toolkit.

  2. Write the component code to actively manage transactions When writing the code required by a component to manage its own transactions, remember the following basic rules...

    • An instance of a stateless session bean cannot reuse the same transaction context across multiple methods called by an EJB client.

    • An instance of a stateful session bean can reuse the same transaction context across multiple methods called by an EJB client.

    The following code extract shows the standard code required to obtain an object encapsulating the transaction context. There are three basics steps involved...

    • The component class must set the value of the javax.ejb.SessionContext object reference in the setSessionContext method.

    • A javax.transaction.UserTransaction object is created by calling a lookup on "java:comp/UserTransaction".

    • The UserTransaction object is used to participate in the transaction by calling transaction methods such as begin and commit as needed. If an enterprise bean begins a transaction, it must also complete that transaction either by invoking the commit method or the rollback method.

    ...
    import javax.transaction.*;
    ...
    public class MyStatelessSessionBean implements SessionBean {
    private SessionContext mySessionCtx =null;
    ...
    public void setSessionContext (SessionContext ctx)throws EJBException {
    mySessionCtx =ctx;
    }
    ...
        public float doSomething(long arg1)throws FinderException,EJBException {
            UserTransaction userTran = (UserTransaction)initCtx.lookup(
               "java:comp/UserTransaction");
            ...
            //User userTran object to call transaction methods
            userTran.begin ();
            //Do transactional work
            ...
            userTran.commit ();
            ...
        }
        ...
    }
    

 

See Also

Developing components to use transactions
UserTransaction interface - methods available
Using local transactions