You are on page 1of 50

EJB Transactions

Agenda
Transaction definitions Overview of java transaction API Declarative transaction management:

ATM transaction example to demonstrate transaction attributes and EJB JTS Explicit transaction management: Transaction aware Stateful session beans
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

EJB deployment descriptor transaction attributes

javax.Transaction.UserTransaction API

Transaction Example
Transfer
Teller Account 1

1. Withdraw

Account 2

2. Deposit

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Transactions define a boundary around a set of operations, so that a series of operations = single unit of work.

A Transaction Is a Unit of Work That Has the Following (ACID) Characteristics:

Atomic: A series of operations appear to

execute as one unit of work: either all operations succeed or none. leave the system in a correct state or abort.

Consistent: The effects of a transaction must Isolated: Concurrent transaction updates are
isolated, intermediate updates are not interleaved with other transactions. Transactions appear to execute serially, even if they are performed concurrently. Durable: When a transaction is completed (committed or rolled back), its effects survive communication process and system failures. Transactions account for system failures reliably using logs.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A Transaction is a series of operations that appear to execute as one Atomic operation, either all operations succeed or none. Performs the necessary concurrency control to guarantee that multiple users concurrently updating data will not corrupt the data ISOLATION: Each transaction should appear to execute independently of other transactions that may be executing concurrently in the same environment. The effect of executing a set of transactions serially should be the same as that of running them concurrently. This requires two things: During the course of a transaction, intermediate (possibly inconsistent) state of the data should not be exposed to all other transactions. Two concurrent transactions should not be able to operate on the same data. Database management systems usually implement this feature using locking.

ACID
Concurrency Control:

Logging and Recovery:

Locking guarantees consistency and Isolation given Atomicity

Guarantees Atomicity and Durability

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Transaction Processing
Characteristics Typically updates data in a database Reliability of transaction results are critical. (All changes or none) Requirements Ability to abort or commit all changes

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Transactions Transactions are a proven technique for simplifying application programming. Transactions free the application programmer from dealing with the complex issues of failure recovery and multi-user programming. If the application programmer uses transactions, the programmer divides the applications work into units called transactions. The transactional system ensures that a unit of work either fully completes, or the work is fully rolled back. Furthermore, transactions make it possible for the programmer to design the application as if it ran in an environment that executes units of work serially.

Transactions

Database

Concurrency control for distributed access to a single resource of data requires coordination and/or synchronization. (locking)

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Global Transactions

Data Base

Data Base

Synchronized access to distributed resources from a single application


Copyright 2000 Sun Microsystems, Inc., All rights reserved.

global transaction management is needed to coordinate transactions between distributed data sources.

2 Phase Commit

Transaction Manager
prepare prepare

ready

ready

Resource Manager
Data Base

Resource
commit/ or rollback commit/ Manager or rollback Data Base

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Two-Phase Commit The two phase commit protocol allows any server that is taking part in a transaction to abort its part of the transaction and, as a result, force the transaction as a whole to be aborted. To achieve this the two phase commit protocol breaks the commitment process into two phases. In the first phase, the transaction manager initiates a vote after it receives a commit request from the client. It sends a prepare message to each server that is participating in the transaction and waits for a response from each server that indicates whether that server can commit or whether it must rollback. Upon receipt of the prepare message each server checks to see if it is able to commit its part of the transaction and then votes for either a commit or an abort accordingly. Once a server has voted to commit a transaction it is not allowed to abort it. This has serious implications for the server because it must ensure that it can commit even in the event of a server failure and restart. Once a server has ensured that it can commit and has cast its vote it is in the preparedstate. When the transaction manager has collected all of votes from the participating servers it initiates the second phase of the protocol. If all of the servers vote to commit the transaction then the transaction manager sends a message to all of the servers telling them to commit their part of the transaction. If one or more servers vote to abort the transaction then the transaction manager sends a message to the servers telling them to abort their part of the transaction.

Transaction Demarcation
Transaction demarcation: a transaction is demarcated meaning that it has a definite beginning and definite end point. Transaction commands:
Begin - start a new transaction. Commit apply all requested operations/changes, end transaction. Rollback - undo all requested operations/changes, end transaction.

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A transaction can be terminated in two ways: the transaction is either committed or rolled back. When a transaction is committed, all changes made by the associated requests are made permanent. When a transaction is rolled back, all changes made by the associated requests are undone.

10

Transaction Context
The transaction context is a pseudoobject that provides transaction metainformation When a transaction is started a transaction context is created. This context is then propagated (transparently) to each participating object in the transaction. Transparently passed from the client or calling object to the server (or called) object.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

11

OMG Object Transaction Service


Transactional Client Transactional Server
Transactional Object Transactional operation

Recoverable Server
Recoverable object resource

begin end

may force rollback

Participates Register resource May force rollback In transaction completion

Transaction Service

Transaction context

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Distributed transaction processing ensures that application processing can span multiple databases on multiple systems coordinated by multiple transaction managers. Transaction processing in a distributed system environment requires the cooperation of three different components: the Transaction Manager (TM) who serves as the transaction coordinator by providing transaction services to the applications, the Resource Manager (RM) who participates in the transaction by performing work on behalf of the applications, and the application program whose business logic requires transaction services. Each of these roles contributes to the Distributed Transaction Processing (DTP) system by implementing different sets of transaction API and functionality. The Object Transaction Service as defined by the OMG spec: Transactional Client The transaction originator. Transactional Object (example is Enterprise Bean) An object that takes part in a transaction. an object whose behavior is affected by being invoked within the scope of a transaction. A transactional object typically contains or refers to persistent data that can be modified by requests. Transactional Server (example is Application Server) A transactional server is a collection of one or more objects whose behavior is affected by the transaction. Resource Manager (example is a driver for a DataBase) Manages a resource (all state that is permanent). The Transaction Service drives the commit protocol by issuing requests to the Resource Manager. Transaction Context Provides transaction meta-information for all transactional objects participating in a transaction. Implicitly propagated to the transactional objects. Resources are registered with the Transaction Service. The Transaction Service drives the commit protocol by issuing requests to the resources registered for a transaction.

12

Java Transaction Service


Application Application Server Resource Manager

EJB Transactional operation

resource

UserTransaction interface

TransactionManager Interface Transaction context

XAResource interface

Transaction Service

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. An application server (or TP monitor) provides the infrastructure required to support the application run-time environment which includes transaction state management. An example of such an application server is an EJB server. A resource manager (through a resource adapter ) provides the application access to resources. The resource manager implements a transaction resource interface that is used by the transaction manager to communicate transaction association, transaction completion, and recovery work. An example of such a resource manager is a relational database server.

13

Java Transaction Service

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

JTS is a Java implementation of the Object Management Group's (OMG) Object Transaction Service (OTS) specification. JTS provides methods for starting, committing, and rolling back transactions, as well as the means to retrieve the current transaction context. Enterprise JavaBeans applications communicate with a transaction service using the Java Transaction API (JTA). JTA provides a programming interface to start transactions, join existing transactions, commit transactions, and rollback transactions. Distributed transaction services in Enterprise Java middleware involve five players: the transaction manager, the application server, the resource manager, the application program, and the communication resource manager. Each player contributes to the distributed transaction processing system by implementing different sets of transaction APIs and functionalities. A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. An application server (or TP monitor) provides the infrastructure required to support the application run-time environment which includes transaction state management. An example of such an application server is an EJB server. A resource manager (through a resource adapter ) provides the application access to resources. The resource manager implements a transaction resource interface that is used by the transaction manager to communicate transaction association, transaction completion, and recovery work. An example of such a resource manager is a relational database server. A component-based transactional application that operates in a modern application server environment relies on the EJB application server to provide transaction management support through declarative transaction attribute settings. In addition, other standalone Java client programs may wish to control their transaction boundaries using a high-level interface provided by the application server or the transaction manager. A communication resource manager (CRM) supports transaction context propagation and access to the transaction service for incoming and outgoing requests. The JTS document does not specify requirements pertaining to communication. The CRM is present to support transaction propagation as defined in the CORBA OTS and GIOP specifications. only high-level interfaces need to be defined to allow transaction demarcation, resource enlistment, synchronization, and recovery process to be driven by the users of the transaction services.

14

Transaction Manager
transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. Initiate and coordinate two-phase commit and recovery protocol with the resource managers.

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

The transaction manager interacts with resource managers using the XA interface

15

Transaction Management
A S
EJB Session

EJB EJB Container


Session EJB

Global Local
Servlet

Container-managed Bean-managed

JTA Transactions JDBC Transactions

Transaction Manager
Data Base

Data Base

Resource Manager

Resource Manager

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. An application server (or TP monitor) provides the infrastructure required to support the application run-time environment which includes transaction state management. An example of such an application server is an EJB server. A resource manager (through a resource adapter ) provides the application access to resources. The resource manager implements a transaction resource interface that is used by the transaction manager to communicate transaction association, transaction completion, and recovery work. An example of such a resource manager is a relational database server.

16

Java Transaction API


UserTransaction interface
Enables application to demarcate transaction boundaries
begin, commit, getStatus, rollback, setRollbackOnly, getStatus, rollback, setRollbackOnly, setTransactionTimeout

Exposed by application server Called by applications Implemented by transaction manager

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. UserTransaction interface: used by client program or session bean (bean managed transaction attribute) standalone Java client programs may wish to control their transaction boundaries using a high-level interface provided by the application server or the transaction manager.

17

Java Transaction API


TransactionManager interface
Allows application server to demarcate transaction boundaries on behalf of managed applications. Called by the application server Implemented by the transaction manager

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Transaction Manager Interface: used by Application Server, provided by Transaction Manager. An application server (or TP monitor) provides the infrastructure required to support the application run-time environment which includes transaction state management. A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation. UserTransaction interface: used by client program or session bean (bean managed transaction attribute) standalone Java client programs may wish to control their transaction boundaries using a high-level interface provided by the application server or the transaction manager. The Transaction Manager is typically a system component of an application server or transaction processing system. The application server provides the infrastructure required to support the application execution environment. The Transaction Manager implements a set of low-level transaction interfaces. The low-level transaction services allow the TM to coordinate transaction processing performed by multiple resource managers, such as database connections, messaging sessions, or connections to backend legacy systems on behalf of the application. Transaction context is propagated, by the TM, to all resource managers that participate in the transaction, even across network connections. The transaction manager (TM) manages global transactions and coordinates the decision to commit them or roll them back, thus ensuring atomic transaction completion. The TM also coordinates recovery activities of the resource managers when necessary, such as after a component fails.

18

XA Interface
Java Application Database 1

Database 2 Transaction Resource Managers (RMs) XAResource Manager (TM)

Database 3

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A Resource is a persistent storage (example Database)


A resource manager (through a resource adapter ) provides the application access to resources. The resource manager implements a transaction resource interface that is used by the transaction manager to communicate transaction association, transaction completion, and recovery work. An example of such a resource manager is a relational database server. A transaction manager provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

19

JTA
XAResource interface
Enables transaction manager to perform three types of operations:
Associate and disassociate transaction work with resources Coordinate transaction completion using the twotwophase commit protocol Perform transaction recovery after crash

Exposed by the resource adapter (driver) Implemented by the resource adapter and
underlying resource manager

Called by the transaction manager


Copyright 2000 Sun Microsystems, Inc., All rights reserved.

20

EJB Transactions
EJB transaction server concept allows platform vendors to add value in the form of scalable, reliable, distributed transactions. Transactions provide an all-or-nothing simple model for managing work. Either all of the objects succeed and all of the work is committed, or one or more of the objects fail and the work is rolled back. Bean clients can drive transactions in two ways: Depend on the declarative transactions specified as part of the EJBs deployment descriptor; Or use the user transaction API (JTA) to explicitly drive transactions from the bean client. Stateful session beans can receive notifications of transaction state.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Declarative Transaction: EJB Container intercepts requests, and based on the deployment descriptor attributes starts a transaction (issues a begin statement) before delegating the method call to the bean. The bean can signal that the transaction should abort if a problem occurs during the method call. When the call completes, then the container issues either a commit or abort statement to the Transaction Manager. Explicit Transaction Management: The client or Session Bean Provider codes transaction demarcation ( begin, commit, abort) using the Java Transaction API.

21

Declarative Transaction Management

The following transaction attributes can be specified in the deployment descriptor to declare what type of transaction support the bean or bean method requires:
TX_NOT_SUPPORTED TX_SUPPORTS TX_REQUIRED TX_REQUIRES_NEW TX_BEAN_MANAGED TX_MANDATORY

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

With Declarative Transaction Management, the container automatically manages the start, enrollment, commitment, and rollback of transactions on behalf of the enterprise bean. Therefore the bean provider does not have to explicitly program transaction demarcation code to participate in distributed transactions.

22

TX_NOT_SUPPORTED
Client/caller
Transaction context1

Server/called bean

client or container tx.begin, call bean, tx.commit or tx.abort

Transaction Context is not propagated. Transaction is suspended until returns. Container performs: utx.suspend Call bean utx.resume

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_NOT_SUPPORTED does not execute in a transaction existing transaction is suspended The NotSupported transaction attribute can be used when the resource manager responsible for the transaction is not supported by the J2EE product. For example, if a bean method is invoking an operation on an enterprise resource planning system that is not integrated with the J2EE server, the server has no control over that systems transactions. In this case, it is best to set the transaction attribute of the bean to be NotSupported to clearly indicate that the enterprise resource planning system is not accessed within a JTA transaction.

23

TX_SUPPORTS
Client/caller
Transaction context1

Server/called bean Transaction


context1

client or container tx.begin, call bean, tx.commit or tx.abort

Transaction context propagated

Client/caller

Server/called bean No Transaction context

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_SUPPORTS does not start a new transaction Can execute in existing transaction Typically, the Supports attribute is used instead of the Required attribute as a performance optimization. However, this optimization should be used with caution. Mission Critical operations should not use this attribute. We do not recommend using the transaction attribute Supports. An enterprise bean with this attribute would have transactional behavior that differed depending on whether the caller is associated with a transaction context, leading to possibly a violation of the ACID rules for transactions.

24

TX_REQUIRED
Client/caller
Transaction context1 client or container tx.begin, call bean tx.commit or tx.abort

Server/called bean Transaction


context1

Transaction context propagated Server/called bean Transaction context1 New Transaction context Created
Container performs: tx.begin Call bean tx.commit or tx.rollback

Client/caller

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_REQUIRED can use existing transaction If not already in transaction will start new one, commit when method completes Required If the client is running within a transaction and it invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method. The Required attribute will work for most transactions. Therefore, you may want to use it as a default, at least in the early phases of development. Because transaction attributes are declarative, you can easily change them at a later time. This transaction attribute should be used whenever the bean is accessing any transactional resource manager. For example, a bean accessing a database through JDBC should use the transaction attribute Required. You should use this if you want the operation to always run in a transaction. The default choice for a transaction attribute should be Required. Using this attribute ensures that the methods of an enterprise bean are invoked under a JTA transaction. In addition, enterprise beans with the Required transaction attribute can be easily composed to perform work under the scope of a single JTA transaction. 25

TX_REQUIRES_NEW
Client/caller
Transaction context1 client or container utx.begin, call bean utx.commit or utx.abort

Server/called bean Transaction


context2

New Transaction context created


Container performs: utx.suspend tx.begin, Call bean, tx.commit/tx.rollback utx.resume

Client/caller

Server/called bean Transaction context1 New Transaction context created


Container performs: tx.begin Call bean , tx.commit or tx.rollback

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_REQUIRES_NEW always starts new transaction, commit when complete Suspends existing transaction The container starts a new transaction for this enterprise bean method and tries to commit the transaction before sending method results to the client. The RequiresNew transaction attribute is useful when the bean method needs to commit its results unconditionally, whether or not a transaction is already in progress. An example of this requirement is a bean method that performs logging. This bean method should be invoked with RequiresNew transaction attribute so that the logging records are created even if the calling clients transaction is rolled back.

26

TX_BEAN_MANAGED
Client/caller
Transaction context1

Server/called bean Transaction


context2

New Transaction context created Client/caller Server/called bean Transaction


context1

New Transaction context created


Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_BEAN_MANAGED bean uses JTA to control transaction Always creates new transaction context In most cases it is better to use declarative transactions as opposed to hard coding bean managed transactions. If one bean method is tx_bean_managed then they all must be.

27

TX_MANDATORY
Client/caller
Transaction context1

Server/called bean Transaction


context1

client or container tx.begin, call bean, tx.commit or tx.abort

Transaction context propagated Server/called bean

Client/caller

Throws Exception
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

TX_MANDATORY must be called within a transaction or will throw exception Use TX_Mandatory when the component is designed only to run within a larger system and you want to mandate that the it is part of a larger operation which starts a transaction before calling the bean. The transaction attribute Mandatory can be used when it is necessary to verify the transaction association of the calling client. They reduce the composability of a component by putting constraints on the calling clients transaction context.

28

Isolation Levels
Isolation levels specify locking levels, for example read-only lock on a row, or write lock. Read-only lock is optimistic,gives better performance. Write lock is pessimistic, ensures better consistency. Pessimistic vs. Optimistic is developer's choice. Isolation levels are set on a DB connection level using database driver JDBC API. Dont mix levels in 1 transaction. Isolation level available depends on DB backend, is not specified in EJB.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Isolation Level An isolation level defines how concurrent transactions to an enterprise information system are isolated from one another. Enterprise information systems usually support the following the isolation levels: ReadCommitted - This level prevents a transaction from reading uncommitted changes from other transactions. RepeatableRead - This level prevents a transaction from reading uncommitted changes from other transactions. In addition, it ensures that reading the same data multiple times will receive the same value even if another transaction modifies the data. Serializable - This level prevents a transaction from reading uncommitted changes from other transactions and ensures that reading the same data multiple times will receive the same value even if another transaction modifies the data. In addition, it ensures that if a query retrieves a result set based on a predicate condition and another transaction inserts data that satisfy the predicate condition, re-execution of the query will return the same result set. Isolation level and concurrency are closely related. A lower isolation level typically allows greater concurrency, at the expense of more complicated logic to deal with potential data inconsistencies. A useful guideline is to use the highest isolation level provided by enterprise information systems that gives acceptable performance. For consistency, all enterprise information systems accessed by a J2EE application should use the same isolation level. Currently, the J2EE specification does not define a standard way to set isolation levels when an enterprise information system is accessed under JTA transactions.

29

Isolation
Isolation ACID Property Operations on shared data are isolated When a transaction begins, your data is locked When the transaction ends, your data is unlocked You choose how isolated you are from others (shared read lock, or exclusive write lock) Challenge: balance safety and concurrency
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

30

Isolation Level
ReadCommitted - This level prevents a transaction from reading uncommitted changes from other transactions RepeatableRead Same as ReadCommitted plus it ensures that reading the same data multiple times will receive the same value even if another transaction modifies the data Serializable - Same as RepeatableRead Plus it ensures that if a query retrieves a result set based on a predicate condition and another transaction inserts data that satisfy the predicate condition, re-execution of the query will return the same result set.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Isolation Level An isolation level defines how concurrent transactions to an enterprise information system are isolated from one another. Enterprise information systems usually support the following the isolation levels: ReadCommitted - This level prevents a transaction from reading uncommitted changes from other transactions. RepeatableRead - This level prevents a transaction from reading uncommitted changes from other transactions. In addition, it ensures that reading the same data multiple times will receive the same value even if another transaction modifies the data. Serializable - This level prevents a transaction from reading uncommitted changes from other transactions and ensures that reading the same data multiple times will receive the same value even if another transaction modifies the data. In addition, it ensures that if a query retrieves a result set based on a predicate condition and another transaction inserts data that satisfy the predicate condition, re-execution of the query will return the same result set. Isolation level and concurrency are closely related. A lower isolation level typically allows greater concurrency, at the expense of more complicated logic to deal with potential data inconsistencies. A useful guideline is to use the highest isolation level provided by enterprise information systems that gives acceptable performance. For consistency, all enterprise information systems accessed by a J2EE application should use the same isolation level. Currently, the J2EE specification does not define a standard way to set isolation levels when an enterprise information system is accessed under JTA transactions.

31

Transaction Example
Transfer
Teller Account 1

1. Withdraw

Account 2

2. Deposit

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

32

Declarative Transaction Management Example


Transfer
New Transaction Context Teller
TC

Transaction Context propagated

Account 1

TC

1. Withdraw
TX_REQUIRES_NEW TX_REQUIRED

Account 2

Transaction Attributes

2. Deposit
TX_REQUIRED

TC

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

33

ATM Transaction Example


Application Server
TX_REQUIRES_NEW TX_REQUIRED

DataBase Server

1)transfer

4)debit

client

Atm
2)App Server register Atm bean BEGIN

Savings Account
7)credit checking Account 8)register bean
resource

5)App Server register Account bean

start prepare 11)commit or rollback

Transaction 3)create New context x Manager 6)add savings bean to context x


9) Add checking bean to context x
10)check context x to see if updates will work

Transaction context

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

34

EJBContext
javax.ejb
<<Interface>> EJBContext

getEJBHome() getCallerIdentity() isCallerInRole()

getUserTransaction() setRollBackOnly() getRollBackOnly()

setRollbackOnly method allows bean to mark the transaction for rollback. getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback.
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

public abstract interface EJBContext The EJBContext interface provides an instance with access to the containerprovided runtime context of an enterprise Bean instance. The setRollbackOnly method allows the instance to mark the current transaction such that the only outcome of the transaction is a rollback. Only instances of a session bean with container-managed transaction demarcation can use this method. The getRollbackOnly method allows the instance to test if the current transaction has been marked for rollback. Only instances of a session bean with container-managed transaction demarcation can use this method.

35

Example without Transaction Control


try { // Withdraw funds from account

} catch (Exception e) { // If an error occurred, do not proceed. } try { // Otherwise, deposit funds into account } catch (Exception e) { // If an error occurred, do not proceed, // and redeposit the funds back into account return; }

fromAccount.withdraw(amount);

toAccount.deposit(amount);

fromAccount.deposit(amount);

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

There are two ways to roll back a container-managed transaction. First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction. If the bean throws an application exception, the roll back is not automatic, but may be initiated by a call to setRollbackOnly. This example illustrates the setRollbackOnly method. If a negative checking balance occurs, withdraw invokes setRollBackOnly and throws an application exception (InsufficientBalanceException). If ejbLoad or ejbStore updates fail, these methods throw an EJBException. Because the EJBException is a system exception, it causes the container to automatically roll back the transaction.

36

Better Way: Container manages transaction


public void transfer(int fromId,int toId,double amount) throws InsufficientFundsException, FinderException { try { fromAccount.withdraw(amount); toAccount.deposit(amount); } catch(InsufficientFundsException ex) { throw new InsufficientFundsException("Insufficient funds " + fromAcctId);

Transaction control will undo deposit or withdraw If either fails


Copyright 2000 Sun Microsystems, Inc., All rights reserved.

There are two ways to roll back a container-managed transaction. First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction. If the bean throws an application exception, the roll back is not automatic, but may be initiated by a call to setRollbackOnly. This example illustrates the setRollbackOnly method. If a negative checking balance occurs, withdraw invokes setRollBackOnly and throws an application exception (InsufficientBalanceException). If ejbLoad or ejbStore updates fail, these methods throw an EJBException. Because the EJBException is a system exception, it causes the container to automatically roll back the transaction.

37

Rolling Back a Container-Managed Transaction


public class AccountBean implements EntityBean { // entity state private double balance; private int accountNumber; // resources private EntityContext context; public void withdraw(double amount)throws InsufficientFundsException { if( balance >= amount ) { balance = balance - amount; } else { context.setRollbackOnly(); throw new InsufficientFundsException (balance); } } }

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

There are two ways to roll back a container-managed transaction. First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction. If the bean throws an application exception, the roll back is not automatic, but may be initiated by a call to setRollbackOnly. This example illustrates the setRollbackOnly method. If a negative checking balance occurs, withdraw invokes setRollBackOnly and throws an application exception (InsufficientBalanceException). If ejbLoad or ejbStore updates fail, these methods throw an EJBException. Because the EJBException is a system exception, it causes the container to automatically roll back the transaction.

38

Transaction Management API


javax.transaction
<<Interface>> UserTransaction

javax.ejb
<<Interface>> EJBContext

begin() commit()
getStatus()

getEJBHome() getCallerIdentity() isCallerInRole()

rollback()
setTransactionTimeout() setRollBackOnly()

getUserTransaction() setRollBackOnly() getRollBackOnly()

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

public abstract interface EJBContext The EJBContext interface provides an instance with access to the containerprovided runtime context of an enterprise Bean instance. The getUserTransaction method returns the javax.transaction.UserTransaction interface. The instance can use this interface to demarcate transactions and to obtain transaction status. Only instances of a session bean with beanmanaged transaction demarcation can use this method. The Java Transaction API, JTA, is implemented by the javax.transaction package. javax.transaction.UserTransaction provides a high level client interface, which allows a bean client to manage the scope of a transaction explicitly. Bean must have method transactional attributes set to TX_BEAN_MANAGED in order to do this. Beans can use the EJBContext to get an UserTransaction object. javax.transaction Interface UserTransaction The UserTransaction interface defines the methods that allow an application to explicitly manage transaction boundaries. void begin() Create a new transaction and associate it with the current thread. void commit() Complete the transaction associated with the current thread. int getStatus() Obtain the status of the transaction associated with the current thread. void rollback() Roll back the transaction associated with the current thread. void setRollbackOnly() Modify the transaction associated with the current thread such that the only possible outcome of the transaction is to roll back the transaction. void setTransactionTimeout(int seconds) Modify the value of the timeout value that is associated with the transactions started by the current thread with the begin method.

39

JTA
UserTransaction interface
Enables application to demarcate transaction
boundaries

begin, commit, getStatus, rollback, setRollbackOnly, getStatus, rollback, setRollbackOnly, setTransactionTimeout

Exposed by application server Called by applications Implemented by transaction manager

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

javax.ejb.EJBContext.setRollbackOnly() method An enterprise bean with container-managed transaction demarcation can use the setRollbackOnly() method of its EJBContext object to mark the transaction such that the transaction can never commit. Typically, an enterprise bean marks a transaction for rollback to protect data integrity before throwing an application exception, because application exceptions do not automatically cause the Container to rollback the transaction. For example, an AccountTransfer bean which debits one account and credits another account could mark a transaction for rollback if it successfully performs the debit operation, but encounters a failure during the credit operation. javax.ejb.EJBContext.getRollbackOnly() method An enterprise bean with container-managed transaction demarcation can use the getRollbackOnly() method of its EJBContext object to test if the current transaction has been marked for roll-back. The transaction might have been marked for rollback by the enterprise bean itself, by other enterprise beans, or by other components (outside of the EJB specification scope) of the transaction processing infrastructure.

40

Explicit Transaction Management Example


public class AtmBean implements SessionBean { javax.ejb.SessionContext ejbContext; javax.transaction.UserTransaction ut; public void transfer(int fromAcctId,int toAcctId,double amount) throws InsufficientFundsException, FinderException { // find account entity beans . . . // get user transaction object ut = ejbContext.getUserTransaction(); // start the transaction ut.begin(); try { fromAccount.withdraw(amount); toAccount.deposit(amount); // commit the transaction ut.commit(); } catch(Exception ex) { ut.rollback(); throw new EJBException (Transaction rolledback);

}
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

To demarcate a Bean Managed transaction, the bean uses JTA to invoke the begin, commit, and rollback methods of the UserTransaction interface. The code demonstrates the UserTransaction methods. The begin and commit invocations delimit the updates to the database. If the updates fail, the code invokes the rollback method and throws an EJBException.

41

Transaction Notification
javax.ejb
<<Interface>> SessionSynchronization

(can) implement

afterBegin() afterCompletion() beforeCompletion()


xxxSessionBean

Motivation: A stateful session bean is a resource too Has in-memory state that needs to rollback in case of failure 1. Alerts your bean to transaction failure Enables you to act as a transactional resource You can undo state changes like a DBMS 2. Alerts you to transaction boundaries Enables you to cache database data for performance
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

javax.EJB Interface SessionSynchronization The SessionSynchronization interface allows a session Bean instance to be notified by its container of transaction boundaries. A session Bean class is not required to implement this interface. A session Bean class should implement this interface only if it wishes to synchronize its state with the transactions. Method Summary void afterBegin() The afterBegin method notifies a session Bean instance that a new transaction has started, and that the subsequent business methods on the instance will be invoked in the context of the transaction. void afterCompletion(boolean committed) The afterCompletion method notifies a session Bean instance that a transaction commit protocol has completed, and tells the instance whether the transaction has been committed or rolled back. void beforeCompletion() The beforeCompletion method notifies a session Bean instance that a transaction is about to be committed.

42

Session Synchronization
public class SellerBean implements SessionBean, SessionSynchronization { private transient boolean success = true; public void afterBegin() { //Transaction has just started. Read in data to cache. } public void beforeCompletion() { // (should write out any database updates it has cached. ) if (!success ) { ctx.setRollbackOnly(); } } public void afterCompletion(boolean state) {
// may need to manually reset its state if a rollback occurred

} }
Copyright 2000 Sun Microsystems, Inc., All rights reserved.

A container-managed session bean can optionally include session synchronization to manage the default auto commit provided by the container. Session synchronization code lets the container notify the bean when important points in the transaction are reached. Upon receiving the notification, the bean can take any needed actions before the transaction proceeds to the next point. SessionSynchronization interface A session bean class can optionally implement the javax.ejb.SessionSynchronization interface. This interface provides the session bean instances with transaction synchronization notifications. The instances can use these notifications, for example, to manage database data they may cache within transactions. The afterBegin notification signals a session bean instance that a new transaction has begun. The container invokes this method before the first business method within a transaction (which is not necessarily at the beginning of the transaction). The afterBegin notification is invoked with the transaction context. The instance may do any database work it requires within the scope of the transaction. The beforeCompletion notification is issued when a session bean instances client has completed work on its current transaction but prior to committing the resource managers used by the instance. At this time, the instance should write out any database updates it has cached. The instance can cause the transaction to roll back by invoking the setRollbackOnly method on its session context. The afterCompletion notification signals that the current transaction has completed. A completion status of true indicates that the transaction has committed; a status of false indicates that a rollback has occurred. Since a session bean instances conversational state is not transactional, it may need to manually reset its state if a rollback occurred.

43

Stateful Session Bean


(With Transactions)
does not exist

1) newInstance() 3)ejbCreate()

ejbRemove()

method-ready
EJB Instance

ejbPassivate()

passive
ejbActivate()

business method

afterBegin()
method-ready In transaction Transactional business method
EJB

afterCompletion(false or true) rollback commit

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

Transaction Manager

44

Exercise: Implement Purchase Method in ShoppingCart Bean

customer

Purchase/Order items in shopping cart

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

45

Transaction Exercise

EJB Container Servlet Shopping Cart


Deplete stock

Product Inventory

Order Entry

create order
EJB Server

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

The Shopping Cart purchaseItems method requires a transaction so that changes will be committed to the database only if updates to Product Inventory AND the creation of the order succeed.

46

ShoppingCartEJB OrderEJB
ShoppingCartEJB
cart numberOfItems addItem () deleteItem() clear() getItems() getItem() getNumberOfItems() getTotal() ejbCreate() setSessionContext() ejbRemove() ejbActivate() ejbPassivate() purchaseCart()

OrderEJB
orderId orderLineItems email s ta tu s totalPrice orderDate

creates

getOrderDetails() ejb Create() ejb R e m o v e ( ) s e t E n tityContext() ejb L o a d () ejbStore() ejb FindByPrimaryK e y() ejb Activate() ejb P a s s ivate()

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

47

OrderEJB
Orders orderid email date ShipAddress Total price
1
getOrderDetails() e jb Create() e jb Re m ove() setEnti tyContext() e jb L o a d () e jbStore() e jbFindByPrimaryK e y() ejb Activate() e jb P a s s ivate()

OrderEJB
o rde rId orderLineItems email s ta tu s totalPrice o rde rDate

0..n

OrderLineItem orderId linenumber ISBN quantity Unit price

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

48

OrderEJB
<<Interface>> Order LineItem getOrderDetails() OrderEJB orderId orderLineItems email s tatus totalPrice orderDate <<Interface>> OrderHome orderId orderLineItems email orderDate status totalPrice create() findByPrimaryKey() getOrderDetails() ejbCreate() ejbRemove() setEntityContext() ejbLoad() ejbStore() ejbFindByPrimaryKey() ejbActivate() ejbPassivate() itemNo qty unitPrice lineNo getItemNo() getQty() getUnitPrice() getLineNo()

OrderDetails orderId lineItems email orderDate status totalPrice getOrderId() getLineItems() getEmail() getOrderDate() getStatus() getTotalPrice()

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

49

Resources
http://www.subrahmanyam.com/ Wiley: Mastering Enterprise JavaBeans By Ed Roman and JavaOne presentation O'REILLY: Enterprise JavaBeans By Richard Monson-Haefel Programming with Enterprise JavaBeans, JTS, and OTS by Andreas Vogel, Madhavan Rangarao

Copyright 2000 Sun Microsystems, Inc., All rights reserved.

50

You might also like