Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering.

Similar presentations


Presentation on theme: "1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering."— Presentation transcript:

1 1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering & Information Sciences

2 2 Distributed Transactions l References: n Tutorial and reference material on the sun web site - Enterprise Edition pages u http://java.sun.com/javaee/5/docs/tutorial/doc/ u Also installed in lab machines. u Look at chapter 34 l Distributed transactions- Intro l Bean managed transactions l Container managed transactions

3 3 Distributed Transactions l A ‘transaction’ keeps user data in a consistent state: n it has an identifiable beginning. n when successfully complete, it is committed. n if something goes wrong during the transaction, the system state (data) can be rolled back. l Example: Transfer money from Account 1 in Bank 1 to Account 5 in Bank 6 n withdraw from Account 1; deposit in Account 5; update history log n if the deposit does not complete successfully, roll back the withdrawal! n if log not updated successfully, roll back deposit, & withdrawal!

4 4 Distributed Transactions …contd l enterprise applications access and store information in one or more databases l because this information is critical for business operations, it must be accurate, current, and reliable. l data integrity would be lost if multiple programs were allowed to update the same information simultaneously l it would also be lost if a system that failed while processing a business transaction were to leave the affected data only partially updated l by preventing both of these scenarios, software transactions ensure data integrity l transactions control the concurrent access of data by multiple programs. l In the event of a system failure, transactions make sure that after recovery the data will be in a consistent state

5 5 l Java EE supports distributed transactions n across multiple databases or multiple application servers l In Java EE there is a choice of two methods for defining transaction boundaries: n Bean-managed transaction demarcation u requires the EJB developer to code the transaction boundaries manually in the EJBs using the Java transaction API (JTA)  methods begin(), commit(), rollback() n Container-managed transaction demarcation u allows the developer to specify transaction boundaries in declarations whilst deploying EJBs Distributed Transactions …

6 6 Container-Managed Transactions l with container-managed transaction demarcation, the EJB container sets the boundaries of the transactions n can be used with any type of enterprise bean: session, or message-driven l simplify development because the enterprise bean code does not explicitly mark the transaction’s boundaries l code does not include statements that begin and end the transaction l by default if no transaction demarcation is specified enterprise beans use container-managed transaction demarcation

7 7 CMT …. contd. l CMTs do not require all methods to be associated with transactions l when developing a bean, can specify which of the bean’s methods are associated with transactions by setting the transaction attributes l enterprise beans that use container-managed transaction demarcation must not use any transaction management methods that interfere with the container’s transaction demarcation boundaries l examples of such methods are the commit, setAutoCommit, and rollback methods of java.sql.Connection or the commit and rollback methods of javax.jms.Session

8 8 Transaction Attributes l A transaction attribute is used to control the scope of a transaction. Controlling the scope is important

9 9 TA values l Required l RequiresNew l Mandatory l NotSupported l Supports l Never l Required l if the client is running within a transaction and invokes the enterprise bean’smethod, the method executes within the client’s transaction l if the client is not associated with a transaction, the container starts a new transaction before running the method

10 10 TA values …contd l RequiresNew l if the client is running within a transaction and invokes the enterprise bean’s method, the container takes the following steps: n 1. Suspends the client’s transaction n 2. Starts a new transaction n 3. Delegates the call to the method n 4. Resumes the client’s transaction after the method completes l if the client is not associated with a transaction, the container starts a new transaction before running the method. l Mandatory l if the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction l if the client is not associated with a transaction, the container throws the transactionRequiredException.

11 11 TA values …contd l NotSupported l if the client is running within a transaction and invokes the enterprise bean’s method, the container suspends the client’s transaction before invoking the method l after the method has completed, the container resumes the client’s transaction l Supports l if the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction l Never l if the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException l In each of the above, if the client is not associated with a transaction, the container does not start a new transaction before running the method

12 12 How to Set Transaction Attributes l transaction attributes are specified by decorating the enterprise bean class or method with javax.ejb.TransactionAttribute annotation, and setting it to one of the javax.ejb.TransactionAttributeType contants l the TransactionAttributeType constants encapsulate the transaction attributes described earlier l Example: l Required: TransactionAttributeType.REQUIRED l …….

13 13 How to use @TransactionAttribute annotation: @TransactionAttribute(NOT_SUPPORTED) @Stateful public class TransactionBean implements Transaction {... @TransactionAttribute(REQUIRES_NEW) public void firstMethod() {...} @TransactionAttribute(REQUIRED) public void secondMethod() {...} public void thirdMethod() {...} public void fourthMethod() {...} }

14 14 Rolling back a CMT l two ways: l 1) if a system exception is thrown, the container will automatically roll back the transaction l 2) by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction l if the bean throws an application exception, the rollback is not automatic but can be initiated by a call to setRollbackOnly

15 15 Synchronizing a Session Bean’s Instance Variables l the SessionSynchronization interface (optional), allows stateful session bean instances to receive transaction synchronization notifications l for example, you could synchronize the instance variables of an enterprise bean with their corresponding values in the database. l the container invokes the Session-Synchronization methods—afterBegin, beforeCompletion, and afterCompletion—at each of the main stages of a transaction

16 16 Bean Managed Transactions l also called application-managed transactions l the code in the session or message-driven bean explicitly marks the boundaries of the transaction l although beans with container-managed transactions require less coding, they have one limitation: l when a method is executing, it can be associated with either a single transaction or no transaction at all l if this limitation will make coding your bean difficult, you should consider using bean-managed transactions

17 17 BMT example begin transaction... update table-a... if (condition-x) commit transaction else if (condition-y) update table-b commit transaction else rollback transaction begin transaction update table-c commit transaction l JDBC or JTA ?

18 18 What is JTA l Java Transaction API l allows you to demarcate transactions in a manner that is independent of the transaction manager implementation l The Application Server implements the transaction manager with the Java Transaction Service (JTS) l code doesn’t call the JTS methods directly l instead, it invokes the JTA methods, which then call the lower level JTS routines. l to demarcate a JTA transaction, invoke the begin, commit, and rollback methods of the javax.transaction.UserTransaction interface

19 19 JTA vs JDBC in a Stateful SB l Note: In a stateless session bean with bean-managed transactions, a business method must commit or roll back a transaction before returning n not required for a stateful session bean l Stateful Session Bean l with JTA transaction, the association between the bean instance and the transaction is retained across multiple client calls n even if each business method called by the client opens and closes the database connection the association is retained until the instance completes the transaction l with a JDBC transaction, the JDBC connection retains the association between the bean instance and the transaction across multiple call n if the connection is closed, the association is not retained.

20 20 BMT Methods l EJBContext interface n getRollbackOnly() not allowed n setRollbackOnly() not allowed l UserTransaction interface n getStatus() n rollback() l methods of java.sql.Connection n commit() n setAutoCommit() n rollback() l getUserTransaction() method of javax.ejb.EJBContext l any method of javax.transaction.UserTransaction

21 21 Transaction Timeouts l for container-managed transactions, the transaction timeout interval can be controlled n by setting the value of the timeout-in-seconds property n in the domain.xml file, which is in the config directory l for example, you would set the timeout value to 5 seconds as follows: timeout-in-seconds=5 l with this setting, if the transaction has not completed within 5 seconds, the EJB container rolls it back l when the Application Server is first installed, the timeout value is set to 0: timeout-in-seconds=0 l if the value is 0, the transaction will not time out

22 22 Updating Several Databases l Java EE transaction manager n controls all enterprise bean transactions except for bean-managed JDBC transactions. n allows an enterprise bean to update multiple databases within a transaction. Updating multiple databases Updating multiple databases across Java EE servers

23 23 Transactions in Web Components a transaction in a web component can be demarcated by using either the java.sql.Connection or javax.transaction.UserTransaction interface l these are the same interfaces that a session bean with bean- managed transactions can use l transactions demarcated with the UserTransaction interface are handled with JTA Transactions l an example of a web component using transactions is Duke’s Bookstore application in the Java EE Tutorial l in the /javaeetutorial5/examples/web/bookstore1/ directory

24 24 Accessing Databases l data that is shared between web components and is persistent between invocations of a web application is usually maintained by a database l web components use the Java Persistence API to access relational databases the data for Duke’s Bookstore is maintained in a database and is accessed through the database access class database.BookDBAO. for example, ReceiptServlet invokes the BookDBAO.buyBooks method to update the book inventory when a user makes a purchase the buyBooks method invokes buyBook for each book contained in the shopping cart, as shown in the following code.

25 25 buyBooks method public void buyBooks(ShoppingCart cart) throws OrderException{ Collection items = cart.getItems(); Iterator i = items.iterator(); try { while (i.hasNext()) { ShoppingCartItem sci = (ShoppingCartItem)i.next(); Book bd = (Book)sci.getItem(); String id = bd.getBookId(); int quantity = sci.getQuantity(); buyBook(id, quantity); } } catch (Exception ex) { throw new OrderException("Commit failed: " + ex.getMessage()); }

26 26 buyBook method public void buyBook(String bookId, int quantity) throws OrderException { try { Book requestedBook = em.find(Book.class, bookId); if (requestedBook != null) { int inventory = requestedBook.getInventory(); if ((inventory - quantity) >= 0) { int newInventory = inventory - quantity; requestedBook.setInventory(newInventory); } else{ throw new OrderException("Not enough of " + bookId + " in stock to complete order."); } } catch (Exception ex) { throw new OrderException("Couldn't purchase book: “ + bookId + ex.getMessage()); }

27 27 buyBooks method in a Transaction try { utx.begin(); bookDB.buyBooks(cart); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch(Exception e) { System.out.println("Rollback failed: "+e.getMessage()); } System.err.println(ex.getMessage()); orderCompleted = false; }


Download ppt "1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering."

Similar presentations


Ads by Google