Usage of UserTransaction inside a EJB Container

Discussions

EJB programming & troubleshooting: Usage of UserTransaction inside a EJB Container

  1. Hi Folks,

    Are there some traps in using UserTransaction inside a EJB Container?

    Can I lookup UserTransaction everywhere (e.g inside of POJOs) inside the container?
    Can I pass a UserTransaction to another POJO Helper class?

    I noticed that UserTransaction interace is not Serializable. From view of performance it's okay not to force it to be Seriazliable.
    So please verify my idea: I cannot saefly pass a UserTransaction instance to a POJO class as the instance is not distributable in a Container cluster.

    So its simply a best practice to use a UserTransaction only inside a single method not share it by delegation and always look it up or get it by the specified Bean method????

    Thx
    Toby
  2. Passing the UserTransaction around is a bad idea. If a POJO needs the UserTransaction, it should look it up itself using JNDI. The JNDI lookup will work pretty much anywhere in the EJB container.

    In general, though, it is a bad idea for lots of methods to interact with the UserTransaction. Only your "top-level" method should use it. This will typically be in your Session EJB, with code like the following:


    UserTransaction transaction = sessionContext.getUserTransaction();
    transaction.begin();
    try {
      // call POJOs ...
      transaction.commit();
    } catch {
      transaction.rollback();
      // handle error: log, rethrow, etc.
    }


    If you try to work with the UserTransaction in your POJO as well, you may find that you are committing or rolling back the transaction more than once, which leads to strange errors.