Java Reference
In-Depth Information
If having to catch exceptions just to call setRollbackOnly seems a little cumbersome
and repetitious, then you're in luck. EJB 3 has a simpler approach to using annotations.
We'll examine exception handling in transactions next.
6.2.5. Transaction and exception handling
Exceptions happen and you must deal with them. Very often exceptions happen when you
least expect them, like in a production system while demoing features to a high-level ex-
ecutive. Because exceptions aren't supposed to occur regularly, it's easy to handle them
incorrectly and not realize it until it's too late. In listing 6.1 there are two exceptions, and
in both cases a rollback is triggered. Let's review the code:
public void placeSnagItOrder(Item item, Bidder bidder, CreditCard card) {
try {
if(!hasBids(item)) {
creditCardManager.validateCard(card);
creditCardManager.chargeCreditCard(card,item.getInitialPrice());
closeBid(item,bidder,item.getInitialPrice());
}
} catch ( CreditProcessingException ce) {
logger.log(Level.SEVERE,"An error ocurred processing the order.",ce);
context.setRollbackOnly();
} catch ( CreditCardSystemException ccse) {
logger.log(Level.SEVERE,"Unable to validate credit card.",ccse);
context.setRollbackOnly();
}
}
As you can see, the CreditProcessingException and CreditCardSystemEx-
ception both trigger a rollback. To avoid this all-too-common mechanical code, EJB
3 introduces the idea of controlling a transactional outcome from an exception using
the @javax.ejb.ApplicationException annotation. The best way to see how
this works is through an example. The following listing reimplements the placeSn-
agItOrder method using the @ApplicationException mechanism to roll back
CMTs.
Search WWH ::




Custom Search