Using Stateless Session Beans


Transactions

When working with beans, you may encounter a situation in which you need to perform multiple updates to several rows. In this case, you want to be sure all of the updates are successful; otherwise, you don't want any of them to succeed. This is called a transaction and is very common in the business world. Resin-EE supports transactions using the javax.transaction package.

Consider an example where you need to update all of the closedate fields in the database:

 try {   Collection c = home.findAll();   Iterator iter = c.iterator();   While (iter.hasNext()) {     Login e = (Login)iter.next();      e.setClosedate(-'2003-1-3 ');   } } catch(Exception e) {} 

Now you want to make sure that all of the updates occur, so you add transaction support:

 Context context = new InitialContext(); UserTransaction transaction = (UserTransaction)context.lookup("java:comp/UserTransaction"); try {   Collection c = home.findAll();   Iterator iter = c.iterator();   transaction.begin();     while (iter.hasNext())       Login e = (Login)iter.next();        e.setClosedate('2003-1-3');     }   transaction.commit(); } catch(Throwable e) {   transaction.rollback(); } 

The code begins by obtaining an object pointer to the current context. Using the context, the JNDI entry to the UserTransaction object is located and assigned to a UserTransaction object. This object is tasked with controlling all updates to the database. Three important methods are associated with the UserTransaction class:

  • begin()— Begins the transaction.

  • rollback()— Causes all updates to be reversed because of an error or other situation.

  • commit()— Causes all of the updates to be committed to the database permanently.

Before you start doing any of the updates, you execute the begin() method to let the UserTransaction object know you are starting a group of updates that need to execute successfully as a unit. After all of the updates have finished, the commit() method is executed to make sure all of the updates are made permanent. If an error occurs during the updates, the rollback() method in the exception executes and all updates are removed.




Mastering Resin
Mastering Resin
ISBN: 0471431036
EAN: 2147483647
Year: 2002
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net