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

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialistica in Informatica – Università di Trento.
Advertisements

21 Copyright © 2005, Oracle. All rights reserved. Oracle Application Server 10g Transaction Support.
Transactions Celsina Bignoli Motivations Atomic operations –Group of operation that must all succeed or all fail Network or machine.
Approaches to EJB Replication. Overview J2EE architecture –EJB, components, services Replication –Clustering, container, application Conclusions –Advantages.
Version # Software Engineering Institute Carnegie Mellon University Pittsburgh, PA Sponsored by the U.S. Department of Defense © 1999 by Carnegie.
Enterprise Java Beans (EJB)
Faculty of Information Technology © Copyright UTS Faculty of Information Technology – TransactionsTransactions-1 Advanced Java Programming Transactions.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
TRANSACTION PROCESSING TECHNIQUES BY SON NGUYEN VIJAY RAO.
Emmanuel Cecchet et al.  Performance Scalability of J2EE application servers.  Test effect of: ◦ Application Implementation Methods ◦ Container Design.
Distributed System Using Java 2 Enterprise Edition (J2EE)
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
EJB. Component Characteristics An enterprise Bean typically contains business logic that operates on the enterprise’s data. An enterprise Bean’s instances.
1 J2EE Components. 2 Application Servers relieve the programming burden for business distributed components. They provide support for system level services.
1 l Enterprise Computing -- 3-tier and multi-tier applications l Enterprise JavaBeans n EJB Features n Types of EJBs l Example – A Currency Converter n.
Enterprise Java Beans - (EJB)
Ing. Ignacio Roqueta ARTech GeneXus and J2EE.
© jGuru.com EJB Transactions. Transactions Simple Transaction –Transaction = more than one statement which must all succeed (or all fail) together.
JDBC Session 3 Tonight’s topics: 1.Connection Pooling 2.Transaction Processing Redux 3.Distributed Transactions 4.RowSets 5.Yet more lab time! (Design.
Enterprise JavaBeans EJB Container Services. EJB container Enterprise JavaBeans are deployed in an EJB container within the application server EJB container.
Lecture 8 Advanced Topics in Enterprise JavaBeans.
EJB Container services Presentation by Arun Kalluri (04/02/2001)
Enterprise JavaBeans Umer Farooq CS6704: Design Patterns & Component FrameworksFebruary 25, 2002.
September 16, 2010COMS W41561 COMS W4156: Advanced Software Engineering Prof. Gail Kaiser
1 Stateful Session Beans Stateless Session Beans Michael Brockway Sajjad Shami Northumbria University School of Computing, Engineering & Information Sciences.
Enterprise Java Bean Matt. 2 J2EE 3 J2EE Overview.
Enterprise JavaBeans. Lesson 1: Introduction to Server-Side Component Software.
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Message-Driven Beans and EJB Security Lesson 4B / Slide 1 of 37 J2EE Server Components Objectives In this lesson, you will learn about: Identify features.
Enterprise Java Bean Computer Networks Natawut Nupairoj, Ph.D. Department of Computer Engineering Chulalongkorn University.
Java Transaction API Sean C. Sullivan
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
J2EE Overview ver 1.0Page 1 © Wipro Technologies Talent Transformation J2EE Overview.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Enterprise JavaBeans Understanding EJB Components Version 0.1 Kamal Wickramanayake
Transaction Services in Component Frameworks Bruce Kessler Comp250CBS March 2, 2004.
Collaborate Lesson 4C / Slide 1 of 22 Collaborate Knowledge Byte In this section, you will learn about: The EJB timer service Message linking in EJB 2.1.
Enterprise Java Transactions Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel.
Introduction to Enterprise JavaBeans Topics In Systems Architecture Barry Herbold
EJB Overview: Constraint Types and Enforcement in JBoss Elissa Newman Fluid Meeting 6/3/04.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Enterprise JavaBeans Session Beans. Session beans are a type of Enterprise JavaBean component designed to implement business logic responsible for managing.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Java Transactions Service Presented by: Dina Sarhan Rana El Hattab.
JPA Transactions
Introduction to EJB. What is an EJB ?  An enterprise java bean is a server-side component that encapsulates the business logic of an application. By.
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
Copyright © 2002 ProsoftTraining. All rights reserved. Enterprise JavaBeans.
红杉树(中国)信息技术有限公司公司 地址:杭州市天目山路 176 号西湖数源软件园 11 号楼 3 层 电话: (86) Transaction & JAVA Fondy Wang 12/7/07.
©NIIT Introducing Enterprise JavaBeans (EJB) Lesson 1A / Slide 1 of 43J2EE Server Components Objectives In this lesson, you will learn about: The features.
Enterprise JavaBeans. Lesson 1: Introduction to Server-Side Component Software.
Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be.
EJB Enterprise Java Beans JAVA Enterprise Edition
EJB. Introduction Enterprise Java Beans is a specification for creating server- side scalable, transactional, multi-user secure enterprise-level applications.
Enterprise Java Beans. Contents  Understanding EJBs  Practice Section.
Transactions and Security. Contents  Transactions  Transaction Support in EJB  Security  Security Support in EJB.
Prepared by Mehmet Küçüksayan Mustafa Ecmel Özdemir
EJB (Enterprise Java Beans)
On transactions, and Atomic Operations
Understanding and Designing with EJB
Objectives In this lesson, you will learn to:
On transactions, and Atomic Operations
Understanding and Designing with EJB
Enterprise Java Beans.
Pre-assessment Questions
Objectives In this lesson, you will learn about:
Presentation transcript:

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

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

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 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 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 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 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 Transaction Attributes l A transaction attribute is used to control the scope of a transaction. Controlling the scope is important

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 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 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 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 How to annotation: public class TransactionBean implements Transaction public void firstMethod() public void secondMethod() {...} public void thirdMethod() {...} public void fourthMethod() {...} }

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 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 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 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 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 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 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 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 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 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 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 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 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 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; }