Transactions by MikeJenny

VIEWS: 26 PAGES: 76

									                         Chapter 10.
                      Transactions in EJB
Source: Ed Roman, Mastering EJB




                                        Jan. 2000




                                       숭실대학교
                                      객체기술연구실
                                  http://object.soongsil.ac.kr



                                                                 1
Contents
 The Benefits of Transactions
 The Motivation for Transactions
 Transactional Models
 Enlist in Transactions with EJB
 Transactional Isolation
 Distributed Transactions
 Programmatic Transactions in EJB




                                                            숭실대학교 객체기술연구실
 Designing Transactional Conversations
 Transaction Examples

                               Ch. 10 Transactions in EJB      2
The Benefits of Transactions
   Transaction
       Appear to execute as one large, atomic
        operation
       Guarantee an all-or-nothing value
        proposition
            All of your operations will succeed, or none of
             them will.
       Allow multiple users to share the same
        data




                                                                              숭실대학교 객체기술연구실
       Guarantee that any set of data they update
        will be completely .

                                                 Ch. 10 Transactions in EJB      3
The Benefits of Transactions
   Component developer
       Can leverage these services through EJB
        products without to complex middleware
        APIs.
       Can harness these services automatically.
       Implicitly from the underlying EJB
        architecture, yielding rapid server-side
        application development.
       Can gain the benefits of transactions




                                                                     숭실대학교 객체기술연구실
        without performing any transaction
        programming.

                                        Ch. 10 Transactions in EJB      4
The Motivation for Transactions
   A few motivational problems that
    transactions address
       Atomic Operation
       Network or Machine Failure
       Multiple Users Sharing Data




                                                                   숭실대학교 객체기술연구실
                                      Ch. 10 Transactions in EJB      5
Atomic Operations
   Classic bank account example
        to transfer funds from one account to another
        There are many problems
    try {
            // withdraw funds from account 1
    }
    catch (Exception e) {
            // if an error occurred, do not proceed.
            return;
    }
    try {
            // otherwise, deposit funds into account 2
    }




                                                                                     숭실대학교 객체기술연구실
    catch (Exception e) {
            // if an error occurred, do not proceed,
            // and redeposit the funds back into account 1.
            return;
    }
                                                        Ch. 10 Transactions in EJB      6
Atomic Operations
   There are many problems with this approach.
      The code is bulky and unwieldy.
      We need to consider every possible
       problem.
           occurs at every step of the way
           code error-handling routines to consider how
            to roll back our changes
        We need to code error-handling routines
         for each step.
           need to code facilities to undo each operation




                                                                              숭실대학교 객체기술연구실
           very tricky and error-prone to write.

        Testing this code is yet another challenge.
             have to simulate logical problems as well as
              failures at many different levels.
                                                 Ch. 10 Transactions in EJB      7
Network or Machine Failure
   Network
       Distributing our application across the
        network introduces failure and reliability
          The network crashes during a banking
           operation.
          An exception will be generated and thrown
           back to the client code.
             This exception is quite ambiguous in nature.
       No way to distinguish between two case.
          The network failed before money was




                                                                                 숭실대학교 객체기술연구실
           withdrew from an account.
          The network failed after withdrew the money.


                                                    Ch. 10 Transactions in EJB      8
Network or Machine Failure
   Machine
       The database is deployed on could also
        crash.
       Crash occurs during a database write
          Inconsistent
          Corrupted state




                                                                    숭실대학교 객체기술연구실
                                       Ch. 10 Transactions in EJB      9
Multiple users Sharing Data
   Multiple users modify the same product
    data simultaneously.
        Operations may become interleaved.
   Needs
        to be a mechanism to deal with multiple
         users concurrently modifying data.

    Client Code
                       Application
                         Server




                                                                      숭실대학교 객체기술연구실
    Client Code
                       Application
    Client Code          Server             table
                                         Ch. 10 Transactions in EJB   10
Transaction Vocabulary
   Transactional Object(=Component)
       An application component
          Such as a banking component is involved in a
           transaction
          Enterprise bean, Microsoft Transaction Server
           component, CORBA component, and so on.
   Transaction Manager
       Responsible for managing the
        transactional operations of the




                                                                          숭실대학교 객체기술연구실
        transactional components.
       Manages the entire overhead of a
        transaction, running behind the scenes to
        coordinate things                    Ch. 10 Transactions in EJB   11
Transaction Vocabulary
   Resource
       A persistent storage from which you read
        or write.
            Database, Massage queue or other storage
   Resource Manager
       Manages a resource.
       Responsible for managing all state that is
        permanent.
       X/Open XA resource manager interface.




                                                                           숭실대학교 객체기술연구실
                                              Ch. 10 Transactions in EJB   12
The ACID Properties
   Atomicity
       If interrupted by failure, all effects are
        undone.
       Operations performed within a transaction
        undergo an all-or-noting paradigm.
   Consistency
       Effects of a transaction preserve invariant
        properties.
       A transaction will leave the system’s state




                                                                      숭실대학교 객체기술연구실
        to be consistent after a transaction
        completes.
                                         Ch. 10 Transactions in EJB   13
The ACID Properties
   Isolation
        Intermediate states are invisible to others.
        Without isolation, your application state
         may become inconsistent.
        Locks on data are automatically assigned
         as necessary.
   Durability
        Effects of a transaction are persistent.




                                                                        숭실대학교 객체기술연구실
        Updates to managed resources, such as
         database records, survive failures.

                                           Ch. 10 Transactions in EJB   14
Transactional Models
   Flat Transactions
       Performed atomically as a single unit of
        work.
       Decide to end the transaction
            Successful transaction is committed.
              All of the persistent operations become permanent
               changes.
            Failed transaction is aborted.
              All changes are rolled back
       Your application may have performed are




                                                                                 숭실대학교 객체기술연구실
        automatically undone by the underlying
        system.
                                                    Ch. 10 Transactions in EJB   15
Transactional Models
   A transaction might abort.
       Invalid parameters passed to one of the
        components.
            called with a null argument, when it was
             expecting a bank account ID string.
       An invariant system state was violated.
            A banking account has a negative balance.
       Hardware of software failure.
            The database is using crashes, the




                                                                               숭실대학교 객체기술연구실
             transaction is rolled back.



                                                  Ch. 10 Transactions in EJB   16
Transactional Models
   The Flat Transaction Process State
                              Final
                                             (Transaction Succeeded)


                                   If all goes well,
                                   commit transaction



        Begin transaction    Transaction
                              Occurring
Initial State
(No Transaction Occurring)

                                   If problem occurs,
                                   Abort transaction




                                                                                     숭실대학교 객체기술연구실
                                            Final State
                                            (Transaction Rolled Back)

                                                        Ch. 10 Transactions in EJB   17
Transactional Models
   How transactional state is rolled back
       Transaction begins, one of your business
        components requests a connection to a
        DB.
       This DB connection is automatically
        enlisted in the transaction.
       Performs some persistent operations
            such as database updates.
       The resource manager waits until a




                                                                               숭실대학교 객체기술연구실
        commit statement has been issued.
       When the transaction is complete.
            The data is persists or not persisted at all.
                                                  Ch. 10 Transactions in EJB   18
Transactional Models
   Nested Transactions
       Consider that your application performs
        the following operations:
          Your application purchases a train ticket from
           Boston, USA to New York, USA.
          Your application purchases a plane ticket from
           to New York, USA to London, England.
          Your application purchases a balloon ride
           ticket from London, England to Paris, France.
          Your application finds out that there are no




                                                                           숭실대학교 객체기술연구실
           outgoing flights from France.


                                              Ch. 10 Transactions in EJB   19
Transactional Models
   Nested Transactions
       Allows you to embed atomic units of work
        within other units of work.
            The unit of work is nested within another unit
             of work can roll back without forcing the
             entire transaction to roll back.
       If the embedded unit can be made to
        succeed
            the larger unit can succeed.




                                                                                 숭실대학교 객체기술연구실
       If the embedded unit of work cannot be
        made to work
            ultimately force the entire unit to fail.
                                                    Ch. 10 Transactions in EJB   20
Transactional Models
   The Nested Transaction Process
                             Final State
                                                     (Transaction Succeeded)

                                           If all goes well,
                                           commit transaction



        Begin transaction         Transaction
                                   Occurring
Initial State
(No Transaction Occurring)                                  If problem occurs,
                                                            Abort transaction


                                Perform one or more




                                                                                             숭실대학교 객체기술연구실
                             smaller-grained transactions

                                                    Final State
                                                    (Transaction Rolled Back)

                                                                Ch. 10 Transactions in EJB   21
Enlisting in Transactions with EJB
   Transaction Models Supported
       Currently Enterprise JavaBeans supports
        only flat transactions.
   Underlying Transaction System
    Abstraction
       Code
            never gets directly involved with the low-level
             transaction system.
       Enterprise beans




                                                                              숭실대학교 객체기술연구실
            Interact with a transaction manager or a
             resource manager.

                                                 Ch. 10 Transactions in EJB   22
Programmatic Vs. Declarative Transactions
   Programmatic Transactions
         Demarcate transactional boundaries
          programmatically.
         Responsible for programming transaction
          logic into your application code.
 Client Code                                             EJB Container/Server

1:call method                2:delegate
                Teller EJB
                 Object                             3:call begin()
                                                                             Transaction
                               Teller Bean     5:call commit()or abort()




                                                                                                        숭실대학교 객체기술연구실
                                                                               Service


                             4:perform
                             business operations

                                                                           Ch. 10 Transactions in EJB   23
Programmatic Vs. Declarative Transactions
   Declarative Transactions
         Allow for components to automatically be
          enlisted in transactions.
         Never explicitly issue a begin, commit, or
          abort statement.
 Client Code                                                      EJB Container/Server

                                           2:call begin()
1:call method   Teller EJB                                                  Transaction
                 Object               5:call commit()or abort()               Service




                                                                                                        숭실대학교 객체기술연구실
                             3:delegate      Teller Bean


                                          4:perform
                                          business operations
                                                                           Ch. 10 Transactions in EJB   24
Controlling
   How EJB are Enrolled in Transactions
        Declarative
             Should automatically be enlisted in
              transactions.
        Programmatic
             Should control its own transactions.
   Transactional attribute
        A required part of each bean’s deployment
         descriptor.




                                                                                 숭실대학교 객체기술연구실
                                                    Ch. 10 Transactions in EJB   25
Setting a transaction
   Setting a transaction attribute
        With BEA WebLogic




                                                                   숭실대학교 객체기술연구실
                                      Ch. 10 Transactions in EJB   26
EJB Transaction Attribute
   Bean Managed Transaction
       TX_BEAN_MANAGED
   Container Managed Transaction
       TX_NOT_SUPPORTED
       TX_REQUIRED
       TX_REQUIRES_NEW
       TX_SUPPORTS
       TX_MANDATORY




                                                                 숭실대학교 객체기술연구실
       TX_NEVER


                                    Ch. 10 Transactions in EJB   27
Bean Managed Transaction
   TX_BEAN_MANAGED
       Bean programmatically controls its own
        transaction boundaries.
       Programming transaction control into
        your source code
            the more traditional way of writing
             transactional code.
       Issue the begin, commit, and abort
        statements




                                                                                숭실대학교 객체기술연구실
            Through the Java Transaction API(JTA)
       In most cases
            Will not need to use programmatic
             transactions                          Ch. 10 Transactions in EJB   28
Bean Managed Transaction
   TX_BEAN_MANAGED
       Must be entirely self-managed.
       Either your whole bean performs transactions
        programmatically or none of it does.
       When using TX_BEAN_MANAGED
          can’t mix transaction attribute on
           different methods on your bean.




                                                                            숭실대학교 객체기술연구실
                                               Ch. 10 Transactions in EJB   29
Bean Managed Transaction
   TX_BEAN_MANAGED
     Client(bean or app)                 TX_BEAN_MANAGED


                                            bean



     Client(bean or app)                 TX_BEAN_MANAGED


                                            bean




                                                                                  숭실대학교 객체기술연구실
     Thread of execution          Client’s transactional context
     Bean’s transaction context   No transactional context

                                                     Ch. 10 Transactions in EJB   30
Container Managed Transaction
   TX_NOT_SUPPORTED
       Your bean cannot be involved in a
        transaction at all.
       If the business method invokes other
        enterprise beans
            the container passes no transaction context
             with the invocation.




                                                                            숭실대학교 객체기술연구실
                                               Ch. 10 Transactions in EJB   31
Container Managed Transaction
   TX_NOT_SUPPORTED
     Client(bean or app)                 TX_NOT_SUPPORTED


                                            bean



     Client(bean or app)                 TX_NOT_SUPPORTED


                                            bean




                                                                                  숭실대학교 객체기술연구실
     Thread of execution          Client’s transactional context
     Bean’s transaction context   No transactional context

                                                     Ch. 10 Transactions in EJB   32
Container Managed Transaction
   TX_REQUIRED
       If you want to always run in a transaction.
       If there is a transaction already running
            Your bean joins in on that transaction.
       If there is no transaction running
            EJB container starts one for you.




                                                                              숭실대학교 객체기술연구실
                                                 Ch. 10 Transactions in EJB   33
Container Managed Transaction
   TX_REQUIRED
     Client(bean or app)                 TX_REQUIRED


                                            bean



     Client(bean or app)                 TX_REQUIRED


                                            bean




                                                                                  숭실대학교 객체기술연구실
     Thread of execution          Client’s transactional context
     Bean’s transaction context   No transactional context

                                                     Ch. 10 Transactions in EJB   34
Container Managed Transaction
   TX_REQUIRES_NEW
       If you always want a new transaction to
        begin when your bean is called.
       If there is a transaction already underway
        when your bean is called.
            Transaction is suspended during the bean
             invocation.
       If there is no transaction running
            EJB container starts one for you.




                                                                              숭실대학교 객체기술연구실
                                                 Ch. 10 Transactions in EJB   35
Container Managed Transaction
   TX_REQUIRS_NEW
     Client(bean or app)                 TX_REQUIRES_NEW


                                            bean



     Client(bean or app)                 TX_REQUIRES_NEW


                                            bean




                                                                                  숭실대학교 객체기술연구실
     Thread of execution          Client’s transactional context
     Bean’s transaction context   No transactional context

                                                     Ch. 10 Transactions in EJB   36
Container Managed Transaction
   TX_SUPPORTS
       If the client calls without a transaction
        context
            TX_NOT_SUPPORTED case.
       If the client calls with a transaction
        context Required case.
            TX_REQUIRED case.




                                                                         숭실대학교 객체기술연구실
                                            Ch. 10 Transactions in EJB   37
Container Managed Transaction
   TX_SUPPORTS
     Client(bean or app)                 TX_NOT_SUPPORTS


                                            bean



     Client(bean or app)                 TX_NOT_SUPPORTS


                                            bean




                                                                                  숭실대학교 객체기술연구실
     Thread of execution          Client’s transactional context
     Bean’s transaction context   No transactional context

                                                     Ch. 10 Transactions in EJB   38
Container Managed Transaction
   TX_MANDATORY
       A transaction must be already running
        when your bean method is called.
       If the client calls without a transaction
        context : exception
            Exception
       If the client calls with a transaction
        context : Required case.
            TX_REQUIRED




                                                                         숭실대학교 객체기술연구실
                                            Ch. 10 Transactions in EJB   39
Container Managed Transaction
   TX_MANDATORY
     Client(bean or app)            TX_MANDATORY


                                       bean



     Client(bean or app)            TX_MANDATORY


                                       bean




                                                                             숭실대학교 객체기술연구실
     Thread of execution     Client’s transactional context
     transaction exception   No transactional context

                                                Ch. 10 Transactions in EJB   40
Container Managed Transaction
   TX_NEVER
       A transaction must not be running when
        your bean method is called.
       If the client calls without a transaction
        context
            TX_NOT_SUPPORTED case
       If the client calls with a transaction
        context : exception
            Exception




                                                                         숭실대학교 객체기술연구실
                                            Ch. 10 Transactions in EJB   41
Container Managed Transaction
   TX_NEVER
     Client(bean or app)            TX_NEVER


                                       bean



     Client(bean or app)            TX_NEVER


                                       bean




                                                                             숭실대학교 객체기술연구실
     Thread of execution     Client’s transactional context
     Transaction exception   No transactional context

                                                Ch. 10 Transactions in EJB   42
Transactional Isolation
   Four transaction Isolation levels in EJB
        TRANSACTION_READ_UNCOMMITTED
           Not offer any isolation guarantees.

           But offers the highest performance.

        TRANSACTION_READ_COMMITTED
           Solves the dirty read problem.

        The TRANSACTION_REPEATABLE_REAㅇ
           Solves the previous problems as well as the
            unrepeatable read problem.
        The TRANSACTION_SERIALIABLE




                                                                           숭실대학교 객체기술연구실
           Solves the previous problems as well as the
            phantom problem.

                                              Ch. 10 Transactions in EJB   43
Transactional Isolation
   Setting a transaction isolation level
        with BEA WebLogic




                                                                  숭실대학교 객체기술연구실
                                     Ch. 10 Transactions in EJB   44
Transactional Isolation Problems
   The dirty read problem
        When application reads data from a database that
         has not been committed to permanent storage yet.
             1. You read integer X from the database. The database
              now contains X=0.
             2. You add 10 to X and save it to the database. The
              database now contains X=10. You have not issued a
              commit statement yet, however, and so your database
              update has not been made permanent yet.
             3. Another application reads integer X from the
              database. The value it reads in is X=10.
             4. You abort your transaction, which restores the




                                                                                      숭실대학교 객체기술연구실
              database to X=0.
             5. The other application adds 10 to X and saves it to the
              database. The database now contains X=20.

                                                         Ch. 10 Transactions in EJB   45
Transactional Isolation Problems
   The unrepeatable read problem
       When a component reads some data from
        a database, but upon rereading the data,
        the data has been changed.
          1. You read a data set X from the database.
          2. Another application overwrites data set X
           with new values.
          3. You reread the data set X from the database.
           The values have magically changed.




                                                                           숭실대학교 객체기술연구실
                                              Ch. 10 Transactions in EJB   46
Transactional Isolation Problems
   The phantom problem
       A new set of data that magically appears in a
        database between two database read operations.
            1. You application queries the database using some
             criteria and retrieves a data set.
            2. Another application inserts new data that would
             satisfy your query.
            3. You perform the query again, and new sets of data
             have magically appeared.
       Difference
            Unrepeatable read problem




                                                                                         숭실대학교 객체기술연구실
               When existing data is changed.
            Phantom problem
               When new data is inserted that didn’t exist before.


                                                            Ch. 10 Transactions in EJB   47
Transactional Isolation Problems
   Transaction isolation Summary
                                           Unrepeatabl
                                  Dirty                     Phantom
          Isolation Level         Reads?
                                           e
                                                            Reads?
                                           Reads?

    TRANSACTION_READ_UNCOMMITTE
    D
                                   Yes        Yes              Yes

    TRANSACTION_READ_COMMITTED     No         Yes              Yes

    TRANSACTION_REPEATABLE_READ    No         No               Yes

    TRANSACTION_SERIALIZABLE       No         No                No




                                                                                 숭실대학교 객체기술연구실
                                                    Ch. 10 Transactions in EJB   48
Distributed Transactions
   Distributed Transaction can
       run across multiple application servers
        and database.
       have components deployed in one
        application server running under the same
        transaction as other components
        deployed in another application server.
       Allow multiple application servers, written
        by different vendors, to collaborate under




                                                                      숭실대학교 객체기술연구실
        one transactional hood.


                                         Ch. 10 Transactions in EJB   49
Two-Phase Commit
   Phase One
       Begins by sending a before commit
        message to all resources involved in the
        transaction.
            The resources involved in a transaction have
             a final chance to abort the transaction.
   Phase Two
       Occurs only if Phase One completed
        without an abort.




                                                                             숭실대학교 객체기술연구실
            All of the resource managers can all be
             located and controlled separately, perform the
             actual data updates.
                                                Ch. 10 Transactions in EJB   50
Two-Phase Commit
   The Two phase commit protocol
       The two-phase commit protocol is useful
          Allows for many transaction managers and
           resource managers to participate in a
           transaction across a deployment.
          If any participant votes that the transaction
           should abort, all participants must roll back.




                                                                            숭실대학교 객체기술연구실
                                               Ch. 10 Transactions in EJB   51
 Two-Phase Commit
                                                   Transaction Participants



                                         Transaction
               1:prepare to commit
                                          Manager

                    2:return

 Transaction                                               Resource manager
                    4:commit             Transaction
 Coordinator
                                          Manager
                    5:return

                                         Transaction
                                          Manager




                                                                                             숭실대학교 객체기술연구실
                                                           Resource manager

3:log result

                 The commit operation is
                 logged in case of a crash.
                                                                Ch. 10 Transactions in EJB   52
Transaction Context
   The most important piece
       Information sent over the transactional
        communications protocol.
   An object
       Holds information about the system’s
        current transactional state.
   Passed around
       Between parties involved in transactions
   Can gain




                                                                      숭실대학교 객체기술연구실
       Insight into whether you’re in a
        transaction.
       What stage of a transaction you are at,
        and other useful data.           Ch. 10 Transactions in EJB   53
Programmatic Transactions in EJB
   OTS(CORBA’s Object Transaction
    Service)
       OMG(Object Management Group)
       A suite of well defined interfaces
          Transaction manager
          Resource Manager

          Transactional objects use to collaborate

       Two parts
            The CosTransactions interface




                                                                                숭실대학교 객체기술연구실
              Transactional objects/components, resources,
               resource managers, and transaction managers use
               to interoperate.
            The CosTSPortability interface
                                                   Ch. 10 Transactions in EJB   54
Programmatic Transactions in EJB
   JTS(The Java Transaction Service)
       A Java mapping of OTS for system-level
        vendors.
       Defines the interfaces
            The interfaces used by transaction managers
             and resource managers behind the scenes.
       The specification does not require the EJB
        Container to support JTS interfaces




                                                                           숭실대학교 객체기술연구실
                                              Ch. 10 Transactions in EJB   55
Programmatic Transactions in EJB
   JTA(The Java Transaction API)
       Use
          Used by component and application
           developers.
          Client and bean code to programmatically
           control transactional boundaries.
       The specification requires that EJB
        Container support
        javax.transaction.UserTransaction
        interface in JTA.




                                                                              숭실대학교 객체기술연구실
            But, it does not require the support for JTA
             Resource Manager and Application Server
             Interface.
                                                 Ch. 10 Transactions in EJB   56
Declarative vs. Programmatic transactions
   Declarative Transactions Examples
       Container-Managed Transactions
       The bean should be deployed with a
        transaction attribute.
            TX_REQUIRED, TX_MANDATORY or
             TX_REQUIRES_NEW

     /**
     * Deposits amt into account.
     */
     public void deposit(double amt) throws AccountException {




                                                                                        숭실대학교 객체기술연구실
              System.out.println(“deposit called.”);
              balance += amt:
     }



                                                           Ch. 10 Transactions in EJB   57
Declarative vs. Programmatic transactions
   Programmatic Transactions Examples
       Bean-Managed Transactions
       The bean should be deployed with a
        transaction attribute.
            TX_BEAN_MANAGED
    public void deposit(double amt) throws AccountException {
       System.out.println(“deposit called.”);
       javax.transaction.UserTransaction ut = ctx.getUserTransaction();
       ut.begin();
       balance += amt:
       try {
             ut.commit();




                                                                                          숭실대학교 객체기술연구실
       }
       catch (Exception e) {
              throw new AccountException(“Deposit failed.”);
       }
    }
                                                             Ch. 10 Transactions in EJB   58
Client Code                                             You must set the JNDI
                                                        Initial Context factory, the
   How to Control Transactions                         provider URL, and any login
    try {                                               names or passwords
                                                        necessary to access JNDI
        // 1 : Set environment
        javax.util.Properties env = new Properties();

      // 2 : Get the JNDI initial context
       Context ctx = new InitialContext(env);

       // 3 : Look up the JTA UserTransaction interface via JNDI
       ut = (javax.transaction.UserTransction)
             ctx.lookup(“javax.transaction.UserTransaction”);

       // 4 : Execute the transaction
       ut.begin();
       // perform business operations
    }




                                                                                              숭실대학교 객체기술연구실
    catch ( Exception e) {
       // deal with any exceptions, including ones indication an abort.
    }



                                                                 Ch. 10 Transactions in EJB   59
Designing Transactional Conversations
   A well-designed stateful session bean
        can salvage its conversations in the case
         of failed transactions.
        A bean class can implement an optional
         interface.
             Called by the container
                afterBegin( ) : directly after a transaction begins.
                beforeCompletion( ) : before a transaction
                  completes.
                afterCompletion( ) : directly after transaction




                                                                                       숭실대학교 객체기술연구실
     public interface javax.ejb.SessionSynchronization {
                  completes.
               public void afterBegin();
              public void beforeCompletion();
              public void afterCompletion(boolean);
     }

                                                          Ch. 10 Transactions in EJB   60
Designing Transactional
   Example of afterCompletion( ) in action:
public class CountBean implements SessionBean, SessioinSynchronization {
          private SessionContext ctx;
          public int val;
          public void ejbCreate(int val) throws CreateException {
                    this.val = val;
          }
          public int count( ) {
                    return ++val;
          }
          public void afterCompletion( boolean b){
                    if(b==false) -- val;
          }
          public void afterBegin(){ }
          public void beforeCompletion() { }
          public void ejbRemove( ) { }




                                                                                       숭실대학교 객체기술연구실
          public void ejbActivate ( ) { }
          public void ejbPassivate( ) { }
          public setSessionContext( SessionContext ctx ) { }
}

                                                          Ch. 10 Transactions in EJB   61
Payment Home Interface
package examples.ejb.basic.payment;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;


public interface PaymentHome extends EJBHome {

 public Payment create(String paymentId, String orderId, String
cardNumber,    double totalPrice) throws CreateException,
RemoteException;

}




                                                                                        숭실대학교 객체기술연구실
                                                           Ch. 10 Transactions in EJB   62
    Payment Remote Interface
package examples.ejb.basic.payment;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface Payment extends EJBObject {

    public int processPayment() throws RemoteException;

    public int changePayment() throws RemoteException;

    public int cancelPayment()throws RemoteException;

    public int getPayment() throws RemoteException;

    public double gettotal() throws RemoteException;




                                                                                           숭실대학교 객체기술연구실
    public double gettotalDollars() throws RemoteException;

}


                                                              Ch. 10 Transactions in EJB   63
 Payment Primary Key Class
package examples.ejb.basic.payment;
public class PaymentPK implements java.io.Serializable {
  public String paymentId;
}




                                                                                        숭실대학교 객체기술연구실
                                                           Ch. 10 Transactions in EJB   64
 Payment Bean Class(1/2)
package examples.ejb.basic.payment;
import javax.jts.UserTransaction;
public class PaymentBean implements EntityBean {
 private transient EntityContext ctx;
 public          String      paymentId; // the primary Key
 public          String      orderId;
 public          int       paymentType;
 public          String      cardNumber;
 public          double       totalPrice;
 public          double       totalDollars; // not persistence
 public void ejbActivate() throws RemoteException {System.out.println("ejbActivate(" + id() +
")");}
 public void ejbPassivate() throws RemoteException {…}
 public void setEntityContext(EntityContext ctx) throws RemoteException {…}
 public void unsetEntityContext() throws RemoteException {…}
 public void ejbLoad() throws RemoteException {…}
 public void ejbStore() throws RemoteException {…}
 public void ejbRemove() throws RemoteException {…}
 public void ejbCreate(String paymentId, String orderId, String cardNumber, double totalPrice) {
   System.out.println("ejbCreate(" + id() + ")");




                                                                                                           숭실대학교 객체기술연구실
   this.paymentId = paymentId;                   this.orderId = orderId;
   this.paymentType = 1;                        this.cardNumber = cardNumber;
   if (orderId.equals(“0000")) this.totalPrice =totalPrice-(totalPrice/10);
   else      this.totalPrice = totalPrice;
   this.totalDollars = totalPrice/1200;
 }
 public void ejbPostCreate(String paymentId, String orderId, String cardNumber,double
totalPrice) {…}                                                               Ch. 10 Transactions in EJB   65
  Payment Bean Class(2/2)
public int processPayment(){
            paymentType = 1;
            System.out.println("Access processPayment : " + paymentType);
            return paymentType;
 }
 public int changePayment(){
            if(paymentType==1) paymentType = 0;
            else                    paymentType = 1;
            System.out.println("Access changePayment : " + paymentType);
            return paymentType;
 }
 public int cancelPayment() {
            paymentType = 0;
            System.out.println("Access cancelPayment : " + paymentType);
            return paymentType;
 }
 public int getPayment() {
            System.out.println("Access getPayment : " + paymentType);
            return paymentType;
 }




                                                                                                           숭실대학교 객체기술연구실
public double gettotal() {
            System.out.println("Access gettotal : " + totalPrice);        return totalPrice;
 }
 public double gettotalDollars() {
            totalDollars = totalPrice/1200;
            return this.totalDollars;
 }}
                                                                              Ch. 10 Transactions in EJB   66
 Payment Deployment Descriptor (1/2)
(EntityDescriptor
 beanHomeName                   payment.PaymentHome
 enterpriseBeanClassName         examples.ejb.basic.payment.PaymentBean
 homeInterfaceClassName          examples.ejb.basic.payment.PaymentHome
 remoteInterfaceClassName        examples.ejb.basic.payment.Payment
 isReentrant                     false
 (controlDescriptors
   (DEFAULT
     isolationLevel          TRANSACTION_SERIALIZABLE
     transactionAttribute    TX_REQUIRED
     runAsMode               CLIENT_IDENTITY
     runAsIdentity           guest
   ); end DEFAULT
 ); end controlDescriptors




                                                                                          숭실대학교 객체기술연구실
                                                             Ch. 10 Transactions in EJB   67
 Payment Deployment Descriptor (2/2)
(persistentStoreProperties
     persistentStoreType           jdbc
     (jdbc
       tableName           ejbPayments
       dbIsShared           false
       poolName            ejbPool
       (attributeMap
         paymentId         pid
         orderId           oid
         paymentType       pt
         cardNumber       cardnumber
         totalPrice        price
       ); end attributeMap
     ); end jdbc
   ); end persistentStoreProperties
 ); end environmentProperties




                                                                                              숭실대학교 객체기술연구실
  ; Entity bean-specific properties:
  primaryKeyClassName             examples.ejb.basic.payment.PaymentPK
  containerManagedFields          [paymentId orderId paymentType cardNumber
totalPrice]
); end DeploymentDescriptor
                                                                 Ch. 10 Transactions in EJB   68
 Client - commit (1/2)
package examples.ejb.basic.payment;
public class Client {
  String url       = "t3://localhost:7001";
  String paymentId, orderId , cardNumber;
  int paymentType;
  String static double totalPrice;
public static void main(String[] args) {
  System.out.println("\nBeginning Payment.Client...\n");
  paymentId = "10035";
  orderId = "3333";
  cardNumber = "12345";
  totalPrice = 30000;
  PaymentPK paymentKey = new PaymentPK();
  paymentKey.paymentId = paymentId;
  UserTransaction utx = null;
  try {
    // Contact the paymentBean container (the "paymentHome") through JNDI.
    Context ctx = getInitialContext();
    PaymentHome home = (PaymentHome) ctx.lookup("payment.PaymentHome");




                                                                                                       숭실대학교 객체기술연구실
    // Find the Payment or create it.
    Payment ac = null;
    try {
        System.out.println("Looking up Payment " + paymentId + "...\n");
        ac = (Payment) home.findByPrimaryKey(paymentKey);
     }catch (Exception ee) { System.out.println("Did not find " + paymentId); }

                                                                          Ch. 10 Transactions in EJB   69
     Client - commit (2/2)
         if (ac == null) {
             System.out.println("Payment " + paymentId+ "\n");
             ac = home.create(paymentId, orderId, cardNumber, totalPrice);
         }
         utx = (UserTransaction)ctx.lookup("javax.jts.UserTransaction");
         utx.begin();
         ac.changePayment();
         utx.commit(); //or utx.rollback();
//       ac.remove();
     }
}




                                                                                                          숭실대학교 객체기술연구실
                                                                             Ch. 10 Transactions in EJB   70
Client’s Window

                  Not Found.




                                                      숭실대학교 객체기술연구실
                     Found.




                         Ch. 10 Transactions in EJB   71
WebLogic Server’s Window

                    Not Found.




                                                        숭실대학교 객체기술연구실
                       Found.


                           Ch. 10 Transactions in EJB   72
MS SQL Server




                                                      숭실대학교 객체기술연구실
     Add pid = “10035”




                         Ch. 10 Transactions in EJB   73
Client Rollback & TX_REQUIRED




                                                    숭실대학교 객체기술연구실
                       Ch. 10 Transactions in EJB   74
Client Rollback & TX_REQUIRES_NEW




                                                         숭실대학교 객체기술연구실
                            Ch. 10 Transactions in EJB   75
 Client Not Use & TX_MANDATORY
 utx = (UserTransaction)ctx.lookup("javax.jts.UserTransaction");
//   utx.begin();
                                                                   Client Code
    ac.changePayment();
//   utx.rollback(); //or utx.rollback();




                                                                                                 숭실대학교 객체기술연구실
                                                                       Exception



                                                                    Ch. 10 Transactions in EJB   76

								
To top