| ||||||||||||||||||||||||||||||||||
|
Find this tutorial in: /usr/local/resin/webapps/resin-doc/amber/tutorial/cmp-xa
Try the Tutorial Demonstrates protecting database updates using some basic transaction patterns. Topics:
See also:
Database Schema
Bean ImplementationThe Course is identical to the basic field bean. It uses FIELD enhancement to define the database columns.
TransactionAttribute REQUIREDThe TransactionAttribute marks the transaction type of the method. The two most common types are REQUIRED and SUPPORTS. A REQUIRED method expects to modify the data and wants to ensure the update is consistent. A SUPPORTS method will only read data, so it can avoid the overhead of a transaction. A transaction is the database equivalent of a synchronized lock. Transactions are somewhat more complicated locks because they need to work with multiple machines and possibly multiple databases, but they're still just sophisticated locks. The typical transaction patterns are similar to familiar lock patterns. A REQUIRED attribute tells Resin that the method must be protected by a transaction. In this case, the swap needs protection from simultaneous threads trying to swap at the same time. A SUPPORTS attribute would tell Resin that the method doesn't need a transaction, but the method should join any transaction that already exists.
Dependency InjectionThe servlet needs to lookup the EntityManager, UserTransaction, and the Swap bean in JNDI.
Since Resin's servlets understand the EJB 3.0 injection annotations, the tutorial can just annotate the setters and let Resin configure them. In other cases, it may be necessary to put the JNDI lookup in the servlet's init() method. SessionBean swapThe first swap in the tutorial switches the teachers using a stateless session bean.
Because the swap method was marked as transaction REQUIRED, Resin will start a transaction if none already exists. If the method exits cleanly, Resin will commit the transaction. If the method throws a RuntimeException, Resin will roll the transaction back. The swap method will throw a runtime exception if the transaction fails to commit. For example, the databse might detect a deadlock and roll the transaction back. UserTransaction swapThe second swap in the tutorial restores the teachers using the underlying UserTransaction. It's essentially identical to the work that the transaction REQUIRED swap method provides. In fact, Resin implements the REQUIRED annotation using UserTransaction.
The main differences between the two are the added capabilities of the REQUIRED.
|