Monday, April 12, 2010

A Gadget for Determining Transaction Attributes for EJB methods

A Java EE greenhorn may find uneasy to determine quickly the appropriate transaction attribute for a method in an enterprise bean. He or she must remember well the definitions of all six attributes in order to choose the right one. Some attribute names are not very self-describing and may be confusing. For example the names of both Required and Mandatory attributes sounds very similar as both say the method must run within a transaction. Of course, there is a nuance that ascribes a stronger sense to the Mandatory attribute. However, especially for programmers for whom English is not the native language it may take a longer time to become familiar with the meanings of all attributes.

I personally prefer to assign a correct attribute in the two-step scenario: in each step I ask myself what I want the EJB container to do when the method is about to be invoked 1) if there is no pending transaction and 2) if there is a pending transaction. I have to choose one answer from the four options:
  1. Create a new transaction
  2. Nothing
  3. Throw an exception
  4. Suspend any pending transaction (makes sense in the second step only)
Once I have chosen the two answers I consult the following table for picking the correct attribute:



The rows in the table represent the two situations (i.e. no transaction and a pending transaction). The columns indicate the possible answers and a cell corresponds to the selected answer. There are six red arrows in the table that join all feasible answers in both situations. Each arrow is accompanied by an attribute’s acronym. Once I have answered the both questions I simply select the arrow connecting the cells and that’s it.

The table can be also useful as a part of the documentation. A cell may contain an explanations and rationale for choosing it as shown in the following example:



Yet, the table can become a part of the method’s JavaDoc. For example:




<h2>TX table</h2>
<table>
<tr>
<td></td>
<td><b>New transaction</b></td>
<td><b>Nothing</b></td>
<td><b>Throw an exception</b></td>
<td><b>Suspend any pending TX</b></td>
</tr>
<tr>
<td><b>No pending TX</b></td>
<td>This method commits changes in the persistent context.</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><b>A pending TX</b></td>
<td>This methods commits the chages even if there is a pending transaction.</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>

No comments:

Post a Comment

About Me

My photo
Cokoliv říkáme, je až na výjimky jinak.

Followers