Saturday, January 23, 2010

Dealing with transactions ( from EJB3 in Action, Chapter 12 - Effectively integrating EJB3 across your application tiers, Manning publications, 2007)

Remember from our discussion in chapter 6 that in your EJB applications you
can use either container-managed transactions (CMT) or bean-managed transac-
tions, in which you programmatically manage transactions using the User-
Transaction API. While CMT is not available in the web container, if your
application uses session beans they allow you to use CMTs and avoid User-
Transaction. We highly recommend you take advantage of CMT. For example,
if you want to make multiple EJB method calls from the same transaction, then
you may be tempted to do the following:
    public class ActionBazaarRegistrationControllerServlet
      extends HttpServlet {
    ...
    //--- Do NOT do this!!! This is NOT recommended!!!
    @EJB ItemManager itemManager;
    @EJB categoryManager categoryManager;
    @Resource private UserTransaction ut;
    ...
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
                 throws ServletException, IOException {
    ...
    ut.begin();
    ...
    categoryManager.addCategory(category);
    itemManager.addItem();
    itemManager.setCategory(category);
    ...
    ut.commit();
    }
    ...
    }
In this example we are injecting the instances ItemManager and CategoryManager
and then invoking several methods on injected session beans. The first issue here
is that you have to write error-prone code to demarcate the transaction. Second,
because your EJBs are fine-grained, the business logic gets scattered between the
EJBs and the web module. Finally, if the EJBs are remote, these translate to three
RMI calls, which can be expensive from a performance perspective. We suggest
you avoid this practice. If your application includes such a requirement, we rec-
ommend you create a session façade and use that to perform all operations, and
then invoke that EJB from the web tier.


No comments: