Ejb Developers Guide

Embed Size (px)

Citation preview

  • 8/12/2019 Ejb Developers Guide

    1/38

    Developers Guide to Understanding Enterprise JavaBeans

    Developers Guide to

    Understanding EnterpriseJavaBeans

    Chris CrenshawNova Laboratories

    www.nova-labs.com

  • 8/12/2019 Ejb Developers Guide

    2/38

    Version 1.4.1

    2 Copyright 1999 Nova Laboratories - Reproduction Prohibited

    For more information about Nova Laboratories or the Developer Kitchen Series, or to addyour name to our monthly mailing list, visit our website at http://www.nova-labs.com

    Nova Laboratories also offers in-house and on-site training and consulting services.

    Nova Laboratories187 Monmouth Park HighwayWest Long Branch, New Jersey 07764

    732-263-9000732-263-0189 (fax)

    This material is copyrighted by Nova Laboratories 1998. This material shall not be reproduced ordistributed in any form without the express written consent of Nova Laboratories.

    All rights reserved.

    The Developer Kitchen is a registered servicemark of Nova Laboratories. Java and all Java-basedtrademarks and logos trademarks or registered trademarks of Sun Microsystems, Inc. in the UnitedStates and other countries. All other products referenced herein are trademarks of their respectiveholders. 1998 Nova Laboratories.

  • 8/12/2019 Ejb Developers Guide

    3/38

    1 - Preface

    Purpose of this Document

    The Enterprise JavaBeans 1.0 Specificationis the formal specification forEnterprise JavaBeans. It formally defines a set of standards for a Javaserver component specification. However, it tends to be targeted more towardthe vendors who need a blueprint describing the mininal requirements forcreating an EJBserver than for developers who are looking to learn about EJB.

    This document is not intended to replace the Specification. The Specification isthe official blueprint for Enterprise JavaBeans. Instead, this document willhopefully serve as a useful primer for developers who want a technicalintroduction to EJB. It attempts to summarize areas of the Specification thatare of particular interest to developers who are trying to learn EJB.

    Nor is this document a tutorial on EJB. Such a document could be severalhundred pages in itself. Instead, its goal is to clearly lay out a detaileddescription of the architecture of EJB, and how the various components fittogether.

    Overall, the purpose of this document is to provide a solid technicalintroduction to EJB. It should benefit both developers looking to start writing

    with EJBas well as developers who need to perform a detailed analysis of EJBto determine whether an EJBsolution is appropriate for their application.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 3

  • 8/12/2019 Ejb Developers Guide

    4/38

    How to read this document

    This document consists of three sections, plus this Preface. Additional sections

    will be added to this document over time that address some of the morespecific advanced features of Enterprise JavaBeans.

    Preface- This section. Defines some basic terms that will be used throughoutthis document. Lists some available documents and products that may beuseful to the reader.

    I nt roducing Enterpri se JavaBeans- This section more fully describes thepurpose of this document. The high-level architecture of EnterpriseJavaBeans is illustrated, along with simplified definitions of the majorcomponents. Also in this section are explanations of how EnterpriseJavaBeans relates to other technologies, such as Java RMI, JavaBeans,and CORBA . Some of the benefits of Enterprise JavaBeans are listed here,along with definitions of the various roles that a developer or vendor may fillin creating an Enterprise JavaBeans solution.

    Underst anding EJB Component s- In this section the reader will get verydetailed definitions of the components of Enterprise JavaBeans. The focus ofthis section is to explain how these components operate in a runtimeenvironment. An attempt is made to describe the minimal behavioralrequirements of the components as defined in the Enterprise JavaBeansSpecification, along with some practical scenarios describing how vendorswill likely implement these components.

    Transactions- Transaction control is a powerful feature of EnterpriseJavaBeans, and can be a very complicated subject. This section will explainhow transactions are used and controlled within Enterprise JavaBeans. Also

    in this section is coverage of the CORBA Object Transaction Service, or OTS.The transaction model in Enterprise JavaBeans is essentially animplementation of OTS, and understanding the interfaces and semantics of thecomponents in OTSwill allow the reader to better understand transactions inEnterprise JavaBeans.

    Defining some basic terms

    EJB- a common abbreviation of Enterprise JavaBeans.

    developer- person who writes implementations of EJBclasses.

    vendor- creator of an EJBproduct that can be used to develop, install, or

    deploy an EJBclass written by a developer. This term is generally used in thisdocument to refer to an organization that has created a server product capableof running EJBclasses written by an EJBdeveloper.

    EJB cl ass- a Java class written and compiled by a developer that conform tothe interfaces and requirements described in the Enterprise JavaBeansSpecification.

    EJB i nstance- an instantiation of an EJBclass.

    Specification- the Enterprise JavaBeans Specification

    Version 1.4.1

    4 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    5/38

    Additional terms will be defined at the appropriate times throughout thisdocument.

    Sources and references

    DocumentationNova Laboratories website containing this document, descriptions andavailability of EJBlecture and workshop training, and source code examples:

    http://www.Nova-Labs.com

    Main page for Enterprise JavaBeans:

    http://java.sun.com/products/ejb

    Enterprise JavaBeans Specificationand other documentation:

    http://java.sun.com/products/ejb/docs.html

    JNDI- Java Naming and Directory Interface:

    http://java.sun.com/products/jndi

    JTS- Java Transaction Service:

    http://java.sun.com/products/jts

    OTS- CORBAservices Object Transaction Service:

    http://www.omg.org/docs/formal/97-12-17.pdf

    Trademarks

    Enterprise JavaBeans , Java, JavaBeans,JDBC, and Java Naming andDirectory Interface are trademarks or registered trademarks of SunMicrosystems, Inc.

    CORBA, CORBAservices, and IIOP are trademarks or registeredtrademarks of Object Management Group, Inc.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 5

  • 8/12/2019 Ejb Developers Guide

    6/38

    Version 1.4.1

    6 Copyright 1999 Nova Laboratories - Reproduction Prohibited

    This page intentionally left blank

  • 8/12/2019 Ejb Developers Guide

    7/38

    2 - I nt roduci ng Ent erpr i seJavaBeans

    Introducing EnterpriseJavaBeans

    Services Framework

    Enterprise JavaBeans is not a product. It is a specification for a Javaserver-side services framework from which vendors can create EJBserverimplementations. The benefit to application developers is that they can focus

    on writing the business logic necessary to support their application withouthaving to worry about implementing the surrounding framework.

    The Specification details certain minimal yet crucial services such astransactions, security, and naming. The vendors must follow thesespecifications to ensure that an enterprise bean can always rely on certainrequired services. The Specification does not state how vendors should goabout implementing these services. While this can make it harder to learn EJBsimply by reading the Specification, it does allows vendors the freedom toprovide enhancements without sacrificing portability regarding core services.

    JavaBeans vs Enterprise JavaBeans

    JavaBeans is the component model for Java. Within theJavaBeans

    Specificationthere are features defined such as events and properties.Enterprise JavaBeans also describes, among other things, a Javacomponent model, but the component model for Enterprise JavaBeans is notthe same as JavaBeans.

    With JavaBeans the emphasis is on allowing developers to visuallymanipulate components in a builder tool. To that end, theJavaBeansSpecificationdescribes in detail the APIs and semantics for inter-component

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 7

  • 8/12/2019 Ejb Developers Guide

    8/38

    event registration and delivery, recognition and utilization of properties,customization, and persistence.

    The emphasis for Enterprise JavaBeans is to detail a model for a servicesframework into which Java components can be portably deployed.Consequently, there is no mention of events, since enterprise beans do nottypically send or receive events. Nor is there mention of properties.Customization does exist, but is not performed at development time usingproperties, but at runtime (deployment time, actually) using a deploymentdescriptor.

    Do not look for similarities between JavaBeans and Enterprise JavaBeans.They are both specifications for component models, but one addresses issuesof application assembly in a builder tool, while the other details a servicesframework into which components can be deployed.

    Dont make the mistake of thinking that JavaBeans is for client-sidedevelopment and Enterprise JavaBeans is for server-side development.JavaBeans can be an appropriate component model for buildingnon-graphical server-side Java applications. The difference is that when you

    use JavaBeans to create a server application, you have to build the entireserver framework. With Enterprise JavaBeans the framework is providedfor you; you simply conform to its APIs. For complex server-side applicationsit is easier to plug in than reinvent.

    Enterprise JavaBeans Architecture

    The EJBserver is the high-level process or application that manages EJBcontainers, along with providing access to system services. The EJBserver mayalso provide vendor-specific features, such as optimized database accessinterfaces, availability of additional services such as CORBAservices,support for SSL3.0, and so forth.

    An EJBserver is required to provide availability of aJNDI-accessible naming

    service and a transaction service.

    Some examples of EJBservers may be:

    database servers

    application servers

    middleware servers

    The EJBcontainer is an abstraction that manages one or more EJBclassesand/or instances. It makes required services available to the EJBclassesthrough an interface defined in the Specification. The container vendor mayalso provide interfaces to additional services implemented either in thecontainer or in the server.

    There is currently no specification for the interface between the EJBserver andthe container. Therefore the container is currently provided by the EJBserver.Once an interface is standardized, it is likely that vendors will createcontainers that can run in any conformant EJBserver.

    The home interfacelists the available factory methods for locating, creating, andremoving instances of EJBclasses. The home objectis the implementation of thehome interface. The developer of the EJBclass must also define the home

    Version 1.4.1

    8 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    9/38

    interface. The container vendor should provide the means to generate thehome object implementation from the home interface.

    The remote interfacelists the business methods in the EJBclass. The EJBObjectimplements the remote interface, and is the object that the client must use toaccess the business methods of the EJBinstance. The EJBclass developerdefines the remote interface, and the container vendor should provide themeans to generate the corresponding EJBObject.

    The client never gets a reference to the EJBinstance, only its EJBObjectinstance. When the client invokes a method, the EJBObject receives the requestand delegates it to the EJBinstance, providing any necessary wrapperfunctionality in the process.

    The clientis an application that uses the home object to locate, create, ordestroy instances of an EJBclass, and uses the EJBObject to invoke thebusiness methods of an instance. The client can be written inJava and useJava RMIto access the home object and EJBObject, or it may be written inanother language using CORBA/IIOP, providing the required server-sidecomponents are deployed in a manner that makes them accessible through

    CORBA interfaces.

    Here is an illustration of the architecture of Enterprise JavaBeans. The nextsection will go into greater detail to describe the individual components.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 9

    Bean

    Bean

    Home

    create()

    remove()

    Remote

    EJBObject

    businessmethods

    Remote

    EJBObject

    business

    methods

    Client

    EJB Server

    EJB Container

    Services

    Transaction

    NamingPersistence

  • 8/12/2019 Ejb Developers Guide

    10/38

    Benefits of Enterprise JavaBeans

    As a developer you should be considering whether Enterprise JavaBeans isappropriate for your application.

    There are considerations when using EJB.

    the EJBserver is a product that you must purchase

    you must implement a minimal API, and understand its semantics

    The advantages far outweigh the disadvantages, especially for more complexapplications.

    Establishing Roles for Application Development

    EJBallows the right person to do the right job. Business developers can focuson writing code that implements business functions. The deployer can takecare of installation issues in a simple and portable fashion. The EJBservervendors will take care of providing support for complex services, and makethem available to the bean often without the knowledge or assistance of thebean developer.

    Automatic Transaction Management

    One of these services transparently provided by the container vendor istransaction control.

    The person writing the business functions does not have to worry aboutstarting and terminating transactions, nor about whether or not the operationsin this business function will work correctly in conjunction with businessfunctions in other beans.

    Distributed Transaction Support

    Part of the transparency of transactions is through distributed transactionsupport. A client can, for example, begin a transaction and then invokemethods on beans in two different servers. Methods in one bean can callmethods in another bean with the assurance that they will execute in the sametransaction context.

    Portability

    With the exception of publicized vendor-specific enhancements, an enterprisebean will install and run in a portable fashion in any EJBserver.

    Scalability

    While the architecture of EJBmay appear to be somewhat complex, youll find

    that the more you understand the architecture, the more youll see that theSpecification was written to allow vendors to provide extremelyhigh-performance implementations. In addition, you should expect to seesuch features as load-balancing and failover once the EJBserver marketmatures.

    Integration with CORBA

    If you are familiar with CORBA, a question may arise regarding the apparentcompetition between CORBA and EJB. But in fact CORBA and EJBare a

    Version 1.4.1

    10 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    11/38

    natural complement to each other. EJBis moving in the direction of usingCORBA/IIOP to provide a more robust transport mechanism. In addition,pure CORBA clients will be able to access enterprise beans as EJBclients.

    CORBAservices provides a wealth of features to an application developer.Rather than trying to replace these services, EJBserver vendors will likelyinclude CORBAservices into their product through a simplified API,allowing bean developers to use CORBAservices without needing to becomeexperts in CORBA. An excellent example of this is the transaction supportprovided by EJBservers to enterprise beans. The transaction service isprobably an implementation of CORBA OTS. For an EJBserver to workcorrectly with CORBA clients, its transaction and naming services will haveto support the CORBA OTSand Naming Service interfaces, respectively.

    Vendor Enhancements

    The real value in Enterprise JavaBeans is the flexibility the specificationallows for vendors to provide their own enhancements. Features likeautomatic object-relational mapping when using container-managedpersistence, gateway services into existing applications, customizable business

    frameworks, and integration of CORBAservices are just a few examples ofadded value that may be provided by vendors.

    Roles in EJB Development

    EJB Developer

    The EJBdeveloper writes EJBclasses using the required classes and interfacesas defined in the Specification. Within this class are the methods for creatingand removing the EJBinstance, along with the business methods of this class.

    The EJBdeveloper is a Java developer with an understanding of the

    interfaces and semantics of Enterprise JavaBeans, and understands thebusiness needs that must be addressed. The EJBdeveloper is responsible forimplementing the functionality of the business applications server side asdiscrete business objects.

    While the EJBcontainer will usually handle all transaction control on behalf ofthe EJBinstance, it is important that the EJBdeveloper understand howtransactions work so that he/she may stipulate to the EJBdeployer thetransactional needs of the various methods in the EJBclass.

    EJB Deployer

    The EJBdeployer is responsible for taking the EJBclass and its supportingclasses and installing them correctly in the EJBserver. The deployer has an

    in-depth understanding of EJBand the characteristics of the runtime serverenvironment, such as database type and location, and so forth.

    The deployer receives the EJBclass requirements from the EJBdeveloper, suchas transactional needs, names and descriptions of required environmentproperties, and so forth.

    The deployer must make these properties, along with their correct runtimevalues, available to the EJBclass at runtime. The deployer is also responsible

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 11

  • 8/12/2019 Ejb Developers Guide

    12/38

    for ensuring that the home object for the EJBclass is available in a namespaceaccessible throughJNDI.

    The EJBdeployer may not be aJava developer nor understand the businessrules that an EJBclass implements, but understands the applicationframework in which the EJBinstance runs.

    For example, the deployer may not understand the details of a databaseapplication written using EJB, but knows the location, schema, andtransactional requirements of the underlying database.The deployer may bethe person to decide critical runtime attributes such as transaction isolationlevels, and so forth. It is important for the EJBdeveloper and deployer tocommunicate clearly to ensure that the EJBclass is deployed with the correctdeployment attributes.

    EJB Container Vendor

    The EJBcontainer vendor provides software to install an EJBclass and itssupporting classes into an EJBserver. The container vendor must also supplyruntime classes that can provide the required services to the EJBinstances at

    runtime. Examples of additional tasks are the generation of stub and skeletonclasses to provide access to the EJBclass home object and EJBObjects,installation of references to the home object in aJNDI-accessible namespace,and availability of a suitable EJBObject implementation that can providecorrect proxy services for the EJBclass.

    EJB Server Vendor

    The EJBserver vendor provides an application framework in which to run EJBcontainers.

    The EJBserver will implement, or provide access to, required services such asaJNDI-accessible naming service and an OTS-compatible transaction service.

    Since there is currently no standard interface between the EJBserver and theEJBcontainer, the EJBcontainer is actually provided by the EJBserver vendor.

    Application Developer

    The application developer writes the client applications that use EJBclasses. Aclient may be a Java applet or application, a servlet, or a natively compiledapplication that uses a CORBA/IIOP interface to access the EJBcomponents.

    The application developer is providing a business application that uses theavailable EJBclasses and methods as abstractions for obtaining low-levelapplication services. This allows the application developer to concentrate onhigh-level functions such as data representation to the user without having to

    worry about how such data is obtained.

    Version 1.4.1

    12 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    13/38

    3 - Underst andi ng t he EJB Component s

    You should now be familiar with the overall architecture of EJB, along with itsmajor components. This section will describe these components inconsiderably more detail, and will explain their runtime behavioral semantics.

    Home Interface

    Factory for Enterprise Beans

    A client needing the use of an enterprise bean creates one through its homeinterface. The home interface lists one or more create()methods that can beused to create an instance of this enterprise bean. This home interface is notimplemented by the bean, but by some other class well call the home object.An instance of this home object is instantiated within the server and madeavailable to clients as a factory for the enterprise bean.

    Locating the Home Object

    A reference to the home object is placed in a naming service that is accessiblefrom the client usingJNDI. The EJBserver will likely provide some sort ofnamespace implementation, although an external namespace could be used.In either case the location of the namespace and theJNDIcontext factory class

    name must be provided to the client initially. For example, a client appletmight receive the namespace location andJNDIcontext factory class name asapplet parameters.

    In addition to providing the location and class name, the client must also havesome knowledge of how to locate the home object within the naming tree.This should also be provided to the client at startup. When the deployerinstalls the enterprise bean into the EJBserver, he/she may have the option ofspecifying a particular location in the naming tree, such as

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 13

  • 8/12/2019 Ejb Developers Guide

    14/38

    ejb/accounting/AccountsPayable. The client must be given thisfully-qualified pathname to locate and obtain the reference to theAccountsPayablehome object.

    It is incorrect to say that a container is made available to clients throughJNDI.Clients look up a home interface implementation usingJNDI. Thatimplementation may be provided by a custom container, but this is avendor-specific detail that should be ignored by both the enterprise beandeveloper and the client.

    Methods in the Home Interface

    The developer that defines ejbCreate()methods in the enterprise bean mustalso declare corresponding create()methods with matching signatures inthe enterprise beans home interface.

    Entity beans may also havefinder methodswhich allow clients to locate existingentity beans based on their identity.

    The home interface is defined as extending from javax.ejb.EJBHome. Thisinterface has the following methods:

    public interface javax.ejb.EJBHome extends Remote {

    public EJBMetaData getEJBMetaData() throws

    RemoteException;

    public void remove(Handle handle) throws

    RemoteException,

    RemoveException;

    public void remove(Object primaryKey) throws

    RemoteException,

    RemoveException;

    }

    The home interface for a bean might look like this:public interface myHome extends EJBHome {

    public myRem create() throws RemoteException,

    CreateException;

    public myRem create(String str) throws

    RemoteException,

    CreateException;

    }

    where

    public interface myRem extends EJBObject { ... }

    The container vendor is responsible for providing the home object whichimplements this home interface, since only the vendor can implement thecode that can act as the factory to create the enterprise beans.

    Version 1.4.1

    14 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    15/38

    Container

    Defining the Container

    In reading the Enterprise JavaBeans 1.0 Specificationthe term containershould not be taken literally as a class, but as a level of responsibility where a

    set of services must be performed on behalf of the bean. A container vendorwill provide a set of tools and classes that run within an EJBserver that fulfillthese responsibilities.

    Some of these services are:

    swapping to and from secondary storage (for session beans)

    persistence management (for entity beans)

    availability of a home object implementing creation and lookup services

    visibility of the home object in aJNDI-accessible namespace

    proper creation, initialization, and removal of beans

    ensuring that business methods run in the proper transaction context

    implementation of certain basic security services generation of stubs and skeletons for remote method invocation on the

    home object and EJBObject

    Container and EJBObject as a Pair

    The Specification often refers to services that may be provided by either thecontainer or the EJBObject. These references are illustrative and do not implyservice requirements of a specific class.

    Both the EJBObject and the container class(es) are provided by the containervendor to support an enterprise bean. Together these classes must fulfill theresponsibilities of the bean container.

    Both the container and the EJBObject have distinct entry points into the bean,giving each a unique ability to provide support for a specific service. Forexample, the container knows which transaction attributes apply to themethods of the bean by reading its deployment descriptor. However, it isthrough the EJBObject that these business methods are invoked.

    The EJBObject must communicate with the container to determine in whattransaction context to call the business method. Once this is determined, theEJBObject must establish this transaction context before invoking the businessmethod.

    All that matters is that the EJBObject and container work together toimplement the services required by a container. The container vendor

    provides the implementations of both objects, and is free to partition this workany way it likes.

    Relationship to the Home Interface

    Vendors currently provide their own tools which read the home interface andgenerate the home objects as containers. In this case the vendor is using aseparate container class for each enterprise bean class.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 15

  • 8/12/2019 Ejb Developers Guide

    16/38

    A container vendor is free to use some other implementation strategy, such asone container class that implements multiple home interfaces, or even astandard container class with separately created custom homeimplementation objects. The only requirement is that the container vendormake a home object available to clients throughJNDI.

    Neither the client nor the bean developer are concerned with theimplementation details of the container and home object.

    Enterprise JavaBean

    The enterprise bean is the class that the developer writes to provideapplication functionality.

    The developer has the option of creating either a session bean or an entitybean, and will make this distinction by implementing the appropriateinterface and declaring its type in the deployment descriptor.

    For session beans:

    public class myBean implements javax.ejb.SessionBean ...

    For entity beans:

    public class myBean implements javax.ejb.EntityBean ...

    The methods in your enterprise bean will never be invoked directly from theclient. The client calls the beans methods indirectly through the EJBObject,which acts as a proxy. In routing all invocations through the EJBObject, thecontainer vendor can insert its own functionality into the invocation throughwrapper code, or method interposition. An example of this would be to create anew transaction context for each method invocation, or to commit or roll backthe transaction when the method returns (to the EJBObject).

    When the container vendors tool generates stubs and skeletons as part of theinstallation process of a bean, it creates a stub and skeleton for the beansEJBObject. It doesnt actually create a stub or skeleton for the bean itself, sinceit is never accessed over the network. The EJBObject is the true networkobject. The bean is the delegate that contains the application-specific businesscode.

    The container may also call certain methods in the bean. For example, thecontainer will ensure that after a new instance of a bean is created, that thearguments used in the call to create()on the home object are passed to thecorresponding ejbCreate()in the bean.

    There are additional interfaces and requirements for enterprise beans.However, these requirements vary based on whether the bean is a sessionbean or an entity bean. These will be covered in the subsequent sections

    detailing session and entity beans.

    Remote Interface

    After writing the enterprise bean the developer created a home interface tospecify the signatures of the creation methods that should be made availableto the client, with the restriction that for each create()method specified inthe home interface, there had to be a corresponding ejbCreate()method inthe bean.

    Version 1.4.1

    16 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    17/38

    In a similar fashion, the developer must create a remote interface whichdescribes the business methods of the bean that the developer would like theclient to be able to invoke.

    Since all client invocations come through the EJBObject, it is the EJBObject, notthe home object, that will formally implement this interface.

    The method names and signatures listed in the remote interface exactly matchthe method names and signatures implemented in the bean. This differs fromthe home interface, whose method signatures matched, but the names weredifferent.

    Here is an example of a remote interface:

    public interface Account extends javax.ejb.EJBObject {

    public void deposit(double amount) throws RemoteException;

    public void withdraw(double amount) throws RemoteException;

    public double balance() throws RemoteException;

    }

    The methods all declare that they may throw a RemoteException, since the

    specification states that the client-side stub is RMI-compliant. Keep in mindthat this does not preclude the stub/skeleton implementation from using adifferent transport, such as CORBA/IIOP.

    The remote interface extends the javax.ejb.EJBObjectinterface, which addsadditional method requirements.

    EJBObject

    The EJBObject is the network-visible object, with a stub and skeleton, that actsas a proxy for the bean. The beans remote interface extends the EJBObjectinterface, and the EJBObject class implements this remote interface, makingthe EJBObject class specific to the bean class. For each bean class there will bea custom EJBObject class.

    Here is the definition of the EJBObject interface, which the beans remoteinterface extends:

    public interface javax.ejb.EJBObject extends java.rmi.Remote {

    public EJBHome getEJBHome() throws RemoteException;

    public Object getPrimaryKey() throws RemoteException;

    public Handle getHandle() throws RemoteException;

    public void remove() throws RemoteException,

    RemoveException;

    public boolean isIdentical(EJBObject other) throws

    RemoteException;

    }

    The EJBObject class that implements this interface is an RMIserver object,since it is implementing an RMIremote interface. Note that the bean itself isnot a remote object and is not visible over the network. When the containerinstantiates this EJBObject class it will initialize it with the reference to thebean instance, so that it may delegate the business method calls appropriately.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 17

  • 8/12/2019 Ejb Developers Guide

    18/38

    The vendor implementation will likely maintain this one-to-one relationshipbetween an EJBObject instance and a bean instance.

    Since the remote interface includes the methods of the EJBObject interface, thebean should obviously not implement this interface, although it does provideimplementations of the listed business methods.

    Since the EJBObject must formally implement the remote interface of the bean,the container vendors generate the EJBObjects source code at beaninstallation time, where the generated code implements the beans remoteinterface. The EJBObject is typically given a unique class name and associatedwith the bean as its EJBObject class.

    Session Bean

    A session bean is an enterprise bean where each instance of a session bean iscreated through its home interface and is private to that client connection. Thesession bean instance cannot be easily shared with other clients. This allowsthe session bean to maintain the clients state.

    An example of this might be a shopping cart bean, where many customers canshop simultaneously, adding to their private cart, instead of everyone addingtheir personal items to a community shopping cart.

    Defining a Session Bean

    You create a session bean by defining a class that implements thejavax.ejb.SessionBeaninterface. The interface is defined as follows:

    public interface javax.ejb.SessionBean extends

    javax.ejb.EnterpriseBean {

    public void ejbActivate() throws RemoteException;

    public void ejbPassivate() throws RemoteException;

    public void ejbRemove() throws RemoteException;

    public void setSessionContext(SessionContext context)

    throws RemoteException;

    }

    The javax.ejb.EnterpriseBeanis an empty interface, and is the supertypefor both session and entity beans.

    Swapping Session Beans

    The container vendor may optionally implement a swapping mechanism tomove instances of session beans from memory to secondary storage,increasing the total number of beans that can appear to be instantiated at a

    time. The implementation would presumably maintain a timeout threshold onits beans, and when a beans inactivity period has reached the threshold, itwould be copied to secondary storage and deleted from memory.

    A container can use any mechanism it chooses to store the bean persistently.The most likely means of doing this would be serialization of the bean. Thebean developer should avoid using transientfields in the bean. Instead, theejbActivate()and ejbPassivate()should be used to maintain the fieldsvalues.

    Version 1.4.1

    18 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    19/38

    Activation and Passivation

    To provide support for swapping by the vendors, the specification formallydefines passivation as the process of swapping out a bean, and activation asthe process of restoring it to memory. The methods ejbActivate()andejbPassivate(),declared in the SessionBeaninterface, allow the containerto tell the bean that it is about to be swapped out, and that it has just beenswapped in. The bean developer can use these methods to release and restorevalues, references, and system resources that should not be held while thebean is in a passivated state. An example of this might be a databaseconnection, since connections are limited resources and cannot be used by abean while it is passivated.

    Using these methods makes the use of transientunnecessary. In fact, usingtransientcan be somewhat unsafe, since it results in fields that are reset tonull or 0 implicitly by the serialization mechanism. It is better that thedeveloper explicitly maintains these fields through the ejbActivate()andejbPassivate()methods.

    Relying onJava serialization to set transientfields to null is also

    non-portable since this behavior would change if this bean were deployed inan EJBcontainer which did not use Java serialization to achieve persistence.

    If the container does not provide swapping, then these methods will never becalled.

    The passivated bean is activated as a result of a business method call from theclient. When the EJBObject receives the method invocation request it informsthe container that the bean must be activated. Once the activation is completethe EJBObject delegates the method call to the bean.

    If the bean is currently in a transaction, it will not be passivated. It is moreefficient to leave the bean in memory, since transactions normally completewithin a fairly short period of time.

    If the bean does not have state that must be released prior to passivation orreset after activation, then these methods can be left empty. In most cases, thebean developer should not expect to have to do anything in these methods.

    Session Bean Management State

    A session beans deployment descriptor must declare the bean as eitherstatelessor stateful. A stateless bean is one which does not maintain any stateinformation between method calls. In general, the benefit of a session bean isthat it does maintain state on behalf of the client.

    However, there is a benefit to having session beans that are stateless. Statelesssession beans are not swapped (or passivated). Since they do not maintain

    state, there is nothing to preserve. The container instead has the option ofdestroying the bean instance. The client is never aware that the bean has beendestroyed. The clients reference is to the EJBObject. If the client later invokesa business method, the EJBObject will work with the container to instantiate anew session bean. Since there is no state, there is nothing else to restore.

    Also, stateless session beans can be shared by clients, with the restriction thatonly one client may be executing a method within the bean at a time. Sincethere is no state maintained between the method calls, any client can use any

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 19

  • 8/12/2019 Ejb Developers Guide

    20/38

    stateless bean instance. This would allow the container to possibly maintain asmaller pool of reusable session beans, saving memory.

    Since a stateless session bean cannot maintain state between method calls, it istechnically an error to define create()methods in the home interface thattake arguments. Passing arguments to the bean during creation implies thatstate may be maintained in the bean after the call to ejbCreate()returns.Furthermore, the container must be able to fully recreate a stateless sessionbean as a result of a business method call on the EJBObject. At that point itwould no longer have the startup arguments that were used to create the beaninitially. The vendors installation tool should check that the home interface ofa stateless session bean does not contain create()methods with arguments.

    Entity Beans

    Role of the Entity Bean

    Entity beans are used to represent underlying objects. The most commonapplication for entity beans is their representation of data in a relational

    database. A simple entity bean can be defined to represent a row in a databasetable, where each instance of the bean represents a specific row. Morecomplex entity beans could represent views of joined tables in a database,where one instance represents a specific customer and all of that customersorders and order items. For these beans there should be considerable demandfor vendor enhancements, such as integrated object-relational mapping.

    In most cases it is both simpler and more efficient to have an entity classrepresent one database table than a set of related tables. Relationship traversalcan be easily added to the entity class definitions, thus maximizing cachereuse and minimizing the presence of stale data.

    Comparing Entity and Session Beans

    It may seem that session beans are not very useful, especially for applicationsthat are database-driven. This is certainly not true. Since an entity beaninstance represents (for example) an underlying row in a database, therelationship between the entity bean instance and the database row is exactlyone-to-one. Since multiple clients must be able to access that underlying row,it means that, unlike session beans, the entity bean instances are sharedamong clients. Since they are shared, they do not allow storage of per-clientstate information.

    Session beans allow the client to store state information on behalf of the client,and the relationship between the client and the session bean instance isone-to-one. Entity beans allow storage of row information, making therelationship between the entity bean instance and the row one-to-one. Anideal solution might be a client which calls into the server through a sessionbean, and the session bean accesses the database through entity beans. Thisallows for storage of state information both for the client and for the rows inthe database.

    Version 1.4.1

    20 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    21/38

    The following diagram illustrates this:

    Client 1 Session Bean

    Session BeanClient 2

    row 2

    row 3

    row 6

    row 7

    row 8

    row 9

    Entity Beans ata aseSession Beans

    Session beans are also invaluable for providing overall control of transactionsacross invocations of methods in the same or different EJBclasses. Withoutsession beans it might be necessary for the application developer (i.e., client

    developer) to understand the transactional requirements of the EJBclasses,and to utilize client-demarcated transactionsto provide transaction control. Onemajor benefit of EJBis that an application developer can write applicationswithout requiring knowledge of the transactional requirements of the EJBclasses. A session bean can be created to represent a business operation, andthat session bean can control the transaction, making client-demarcatedtransactions unnecessary.

    Finder Methods

    Creating and removing bean instances, either through the home or remoteinterface, have different meanings for entity beans than session beans. Forsession beans, removingmeans the bean instance is removed from the

    container and cannot be used again, and its state information is lost. For entitybeans, removal means that the underlying row in the database is deleted. Forthis reason, removal is not considered a part of the typical lifecycle of theentity bean.

    The only way to have a session been is to create it. Creating an entity beanmeans that a row is inserted into the database. Similar to the removaloperation, the creation operation is generally not considered part of thetypical lifecycle of an entity bean.

    For a client to get access to an entity bean, itfindsit. In addition to create()methods, the home interface of an entity bean will also havefinder methods.The client must determine some means of identifying the specific row based

    on some application qualification. For example:public interface AccountHome extends EJBHome {

    public Account findByFirstLast(String first, String last)

    throws RemoteException, FinderException;

    public Account findByAccountNumber(String acctNum)

    throws RemoteException, FinderException;

    }

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 21

  • 8/12/2019 Ejb Developers Guide

    22/38

    When the client invokes one of these methods on the home object, thecontainer passes the invocation to the corresponding method in the entitybean.

    public class myEntityBean implements EntityBean {

    ...

    public Object ejbFindByFirstLast(String first, String last){

    // runs appropriate singleton SELECT statement

    // returns primary key for selected row

    }

    public Object ejbFindByAccountNumber(String acctNum) {

    // runs appropriate singleton SELECT statement

    // returns primary key for selected row

    }

    }

    A good way to think of each finder method is as a database SELECTstatement,where the dynamic SQLparameters are supplied as the method arguments.

    Notice that the finder methods in the home interface return a remote reference(to the EJBObject) back to the client. The finder methods in the bean return aunique identifier, orprimary key, to the container. The container will take thisprimary key and use it to instantiate a new EJBObject to represent the selectedrow. Regardless of the implementation of the finder method, the selected rowis always represented to the container using a primary key. It is up to theentity bean class to decide how to construct a primary key to uniquelyidentify the row.

    It is likely that a finder method may find several rows that meet the criteria inthe SELECTstatement. In this case the beans finder method is defined toreturn an enumeration of primary keys. The finder method in the homeinterface is defined to return to the client an enumeration of EJBObject

    references.

    public interface AccountHome extends EJBHome {

    ...

    public Enumeration findByCompany(String companyName)

    throws RemoteException,

    FinderException;

    }

    public class myEntityBean implements EntityBean {

    ...

    public Enumeration ejbFindByCompany(String companyName) {

    // runs appropriate SELECT statement

    // returns an Enumeration of primary keys

    }

    }

    Primary Key

    The termprimary keycan be misleading. It would be more appropriate toconsider it a unique identifier. In the case of an entity bean that represents a

    Version 1.4.1

    22 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    23/38

    row in a table, the primary key might be a representation of the values of thecomposite key for that row.

    For every entity bean instance, there is a corresponding EJBObject. When anEJBObject is paired with an entity bean instance, the primary key of theinstance is stored in its EJBObject.

    This entity bean instance is said to now have an identity.When the client invokes a finder method on the home object, the containerwill use an entity bean instance that has no identity to perform the request.The container may privately hold one or more of these anonymous instancesfor this purpose. Regardless of the implementation of the finder method, itsimplementation in the bean will always return to the container just theprimary key of the underlying data, such as the row in the database. Ifmultiple rows met the search criteria, then multiple primary keys are returnedto the container.

    Now that the container has the primary key (or keys) it will instantiate anEJBObject (or EJBObjects) and initialize them with the primary keys. Thecontainer then has the option of also instantiating the entity bean instances to

    associate with each EJBObject. Since the identity of the underlying row isactually in the EJBObject, there would be no state within the bean instances.For this reason, the container may defer the instantiation of the bean instancesuntil a business method request is made on the EJBObject, conservingmemory resources.

    When a finder method returns a primary key to the container, the containerwill first check to see if an EJBObject with that primary key already exists. Ifso, the container will not create a new EJBObject, but will return the referenceto the existing EJBObject to the client. This assures that there is only oneEJBObject instance per row, and that all clients share the EJBObjects.

    The primary key uniquely identifies the bean instance only within its class, or

    home. The container is responsible for ensuring this distinction.It is important to remember that the purpose of the finder methods is toextract only primary key data from the database. The actual column data forthe row is not extracted. It is likely that no entity bean instances are allocatedas a result of the call to a finder method. Only the EJBObjects containing theprimary keys are allocated. The entity bean instances will be allocated andloaded at a later time as a result of a clients method call on the EJBObject.

    The home object will always make the following method available to clients:

    public myRem findByPrimaryKey(Object key) throws ...;

    The EJBObject provides an implementation of the following method:

    public Object getPrimaryKey();

    The client can obtain the primary key of an entity at any time, and use theprimary key at a later point in time to re-establish a reference to the entitythrough its home interface.

    The class type of the primary key is specified in the deployment descriptor.The bean developer may represent the primary key using any class type. Theonly requirement is that the class must implement Serializable, since itmust be possible to pass the primary key between the client and server.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 23

  • 8/12/2019 Ejb Developers Guide

    24/38

    Swapping Entity Beans

    Now would be a good time to look at the javax.ejb.EntityBeaninterface.

    public interface javax.ejb.EntityBean extends EnterpriseBean {

    public void ejbActivate() throws RemoteException;

    public void ejbPassivate() throws RemoteException;

    public void ejbRemove() throws RemoteException,

    RemoveException;

    public void setEntityContext(EntityContext ctx)

    throws RemoteException;

    public void unsetEntityContext() throws RemoteException;

    public void ejbLoad() throws RemoteException;

    public void ejbStore() throws RemoteException;

    }

    Activation and passivation work in a similar fashion to session beans.However, entity beans are stateless when they are not in a transaction; theirstate is always synchronized with the underlying data store. If we apply thesame rules for swapping that we used for session beans, then we would notswap out a stateless entity bean, we would just destroy it. However, since thecontainer needs anonymous entity beans to invoke the finder methods, thecontainer will likely passivate entity beans into a private in-memory pool forthis purpose. Once the entity bean instance is taken away from the EJBObject,it no longer has an identity (or primary key association).

    The container may also use this in-memory pool for re-allocation of entitybeans when a business method is requested on an EJBObject that has nocorresponding entity bean.

    Remember that when a bean is in this pool it has no identity and can bereused by any other EJBObject. The container may implement a policy which

    does not maintain any entity beans with EJBObjects, except when a businessmethod is currently be executed through that EJBObject. More properly, theentity bean would remain associated with the EJBObject while the bean isinvolved in a transaction.

    Bean-Managed Persistence

    Since an entity bean represents underlying data, we need to fetch the datafrom the database and place it in the bean. When the container first associatesan entity bean instance with an EJBObject, it starts a transaction and invokesthe ejbLoad()method of the bean. Within this method the developer mustprovide the code that will extract the appropriate data from the database andplace it in the bean. When the container wishes to commit the transaction it

    will first invoke the beans ejbStore()method. This method is responsiblefor writing the data back to the database.

    We call this bean-managed persistence, since is the code within the beansmethods that provide this synchronization.

    When the ejbLoad()method completes, there is the potential for the bean tobecome out of synch with the underlying database. The business methodinvocation which triggered the allocation of the bean to the EJBObject, andsubsequent ejbLoad(),must be declared in the deployment descriptor to run

    Version 1.4.1

    24 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    25/38

    within a transaction. Upon receiving the business invocation request, theEJBObject will work with the container to establish a transaction context. Thecontainer will then allocate the bean to the EJBObject and invoke the beansejbLoad()method. This method is now running in the context of atransaction. This transaction context is passed to the database, where theaccessed rows in the database become locked by the transaction, according to

    the transaction isolation level specified in the deployment descriptor.The rows in the database remain locked as long as the transaction context isalive. When the transaction is about to be committed, either by the client orthe container, the container will first invoke the beans ejbStore()method,causing the bean to flush its data to the database.

    Keeping the appropriate database rows locked between the ejbLoad()andejbStore()ensure that the bean is always synchronized with the database.Multiple business method invocations could occur during this time. Morespecifically, the ejbLoad()and ejbStore()demarcate the transactionboundaries, and multiple business method invocations can occur within thetransaction.

    The duration of the transaction is determined by the deployment descriptor,and possibly by the client.

    Note that the ejbActivate()and ejbPassivate()methods should not beused to perform synchronization with the database.

    Container-Managed Persistence

    If the deployment descriptor declares that the bean will utilizecontainer-managed persistence, the ejbLoad()and ejbStore()methods willnot be used to access the database. The container will load the data from thedatabase into the bean and then invoke the beans ejbLoad()method to tell itthat it has just received data from the database.

    Likewise, the container will invoke the beans ejbStore()method to tell itthat its data is about to be written to the database. These methods do notactually perform any database operations.

    While a vendor may provide sophisticated tools to accomplish this, such asautomatic generation of entity bean classes utilizing object-relationalmapping, the specification describes a minimal set of requirements for avendor to provide container-managed persistence.

    The deployment descriptor can specify a simple mapping of publicfields inthe bean to columns in the database. The container uses this to read the publicfields from the bean and write them into the appropriate columns, and to readthe database columns and write them into the public fields.

    While container-managed persistence can be a great service to EJBdevelopers,without having a more sophisticated mechanism, such as object-relationalmapping, the developer may find it more effective to use bean-managedpersistence.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 25

  • 8/12/2019 Ejb Developers Guide

    26/38

    Deployment Descriptor

    Distinguishing EJB Development Roles

    There are two primary roles for EJBdevelopment, the bean developer and thebean deployer.

    There are a number of attributes which cannot be predicted by the developer,such as network addresses of databases, database drivers to use, and so forth.The deployment descriptor acts as property sheet which can defined by thedeveloper, and filled in with correct values by the deployer. The deploymentdescriptor is a standard format, and so is portable between the developmentand deployment environments, even when different EJBplatforms are used.

    Controlling the Behavior of Enterprise Beans

    In addition to providing a standard property sheet for collaboration betweendevelopment and deployment time, the deployment descriptor also containsdetailed information about how the bean should execute regardingtransactions and security. Certain attributes, such as access control lists, willlikely be adjusted by the deployer to ensure that the appropriate users canutilize the beans at runtime. Other attributes, such as transaction information,will probably be specified completely by the developer, since it is thedeveloper who created the database access code and has intimate knowledgeof how the beans methods should run regarding transactions.

    Defining the Deployment Descriptor

    The deployment descriptor is a standard Java class. An instance is created,populated with values, and serialized. This serialized deployment descriptoris placed in a jar file and sent to the deployment area along with the enterprisebean classes. The deployer will read in the serialized deployment descriptor,possibly modify some values, and use this modified deployment descriptor toinstall the enterprise bean.

    Here are the contents of the deployment descriptor. It is the superclass to twoother deployment descriptor classes. The subclasses are the descriptorsactually used to describe the bean.

    javax.ejb.deployment.DeploymentDescriptor

    bean home name

    bean class name

    home interface class name

    remote interface class name

    environment properties

    control descriptors

    access control list

    These two classes are subclasses of DeploymentDescriptor:

    javax.ejb.deployment.SessionDescriptor

    state management type

    session timeout

    Version 1.4.1

    26 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    27/38

    javax.ejb.deployment.EntityDescriptor

    list of container-managed fields

    primary key class name

    This descriptor defines transaction and security attributes for the entire beanand for individual methods. An array of these objects are specified in

    DeploymentDescriptor.javax.ejb.deployment.ControlDescriptor

    transaction isolation level

    Methodobject to which this descriptor applies

    run-as mode (for identity mapping)

    run-as identity (for identity mapping)

    transaction attribute

    To deploy an enterprise bean the appropriate descriptor is allocated,initialized, and serialized, and placed in the jar file along with the enterprisebean classes.

    Each vendor may have a different means for defining a deploymentdescriptor. One may use a text specification file, for instance, while anotherprovides a graphical tool. The end result is a descriptor which is in a standardformat, and is portable across vendor platforms.

    EJB Jar File

    To package the enterprise bean, the bean classes, including the interfaces, andthe serialized deployment descriptor are placed in a jar file. This jar file musthave a manifest file entry which declares the deployment descriptor as anenterprise bean.

    Name: AccountDD.ser

    Enterprise-Bean: true

    It is the deployment descriptor, not the bean class, that is listed in the manifestas an enterprise bean. The deployment descriptor provides the full descriptionof all the files in the jar that together define the enterprise bean.

    The developer should not have to be concerned with the creation of the EJBjarfile. The vendor should provide a tool which will assist the developer increating the deployment descriptor, and then package all the necessary filesinto a jar with the appropriate manifest file entries.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 27

  • 8/12/2019 Ejb Developers Guide

    28/38

    Version 1.4.1

    28 Copyright 1999 Nova Laboratories - Reproduction Prohibited

    This page intentionally left blank

  • 8/12/2019 Ejb Developers Guide

    29/38

    4 - Transact i ons

    CORBA OTS

    The transaction model used in EJBsimilar to OTS. In fact, CORBA-compliantEJBservers must provide an OTS-compliant transaction service.Understanding how OTSworks helps to understand how transactions work inEJB.

    Defining TransactionsA transaction is formally defined as an atomic unit of work. Multipleoperations can be included in a transaction, and when the transaction isterminated, all changes performed by the operations are either applied orundone as a whole. These operations are called commitand rollback.

    Transactions are used extensively with database applications. Good databaseproducts provide very strong support for transactions. Rows that are accessedduring a specific transaction become locked and stay locked for the durationof the transaction. Based on the database product there can be multiplelocking levels which can be selected prior to the start of the transaction. Theappropriate locking level should guarantee integrity of the data whileoptimizing concurrency of access for operations in other transactions.

    Transactions may also be distributed across the network, such as a clientaccessing two different databases from within a single transaction. To supportdistributed transactions most transaction managers (including databases)support two-phase commits. This is a simple protocol where the transactionmanager first asks all participants if their work is finished and would like toattempt to commit their work. This is the first phase of the protocol. Onceeveryone agrees to commit, the second phase begins. The transaction managergives the command to perform their individual commit operations.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 29

  • 8/12/2019 Ejb Developers Guide

    30/38

    Key Components in OTS

    To better understand how OTSworks we need to look at its key components.The following components can be mapped almost directly to EJB, andunderstanding how these components work in OTSwill provide a goodfoundation for understanding transactions in EJB.

    Control Terminator

    Coordinator

    Resource

    Synchronization

    The following diagram illustrates the significant methods defined for theseobjects, and how the objects fit into the transaction architecture.

    The dashed box represents a transaction. Within the transaction are all of theobjects participating in the transaction. Commits and rollbacks will be appliedto all the Resourceobjects in this group.

    The Controlobject represents the transaction. From this object we can obtainthe Coordinatorand the Terminator. An EJBdeveloper never sees theControlobject. It is used by the container to manage the transaction on behalfof the bean.

    The Terminatoris also used by the container to commit or roll back the

    transaction when a thread returns from a bean method where the method isdescribed in the deployment descriptor as requiring the container to terminatethe transaction upon completion of the method. When a commit or rollback isrequested, all the objects in the transaction will be committed or rolled back,as appropriate.

    The Resourceis the object that has transactional state. For example, it may bea connection to a database. Calling commit()on this object would cause thedatabase updates to be applied to the database. A rollback()would revertall changed made to the database through this connection since the start of the

    Version 1.4.1

    30 Copyright 1999 Nova Laboratories - Reproduction Prohibited

    commit()

    rollback()

    commit()

    rollback()

    Resource

    before_completion()

    after_completion(Status s)

    before_completion()

    after_completion(Status s)

    get_terminator()

    get_coordinator() Synchronization

    Control

    commit()

    rollback()

    register_resource(Resource r)

    register_synchronization(Synchronization s)

    rollback_only()

    Terminator Coordinator

    Transaction

  • 8/12/2019 Ejb Developers Guide

    31/38

    transaction. Once the commit or rollback completed, the corresponding rowsin the database would be unlocked. The level of locking applied would havebeen specified in the deployment descriptor. The full set of methods for thisobject would show that these objects actually implement the two-phasecommit protocol, allowing each object to vote as to whether the entiretransaction should be committed or rolled back.

    The Synchronizationis an object that wishes to be notified upon completionof the transaction whether the transaction was committed or rolled back.Unlike the Resource, it does not participate in the two-phase commit protocoland has no vote as to whether the transaction should be committed or rolledback. It plays a passive role in the transaction. This is the role that a sessionbean may play by implementing a special interface.

    The Coordinatoris the object that makes all this work. Through this objectboth Resourceobjects and Synchronizationobjects are registered in thetransaction. The bean does not get access to this object directly.Transaction-aware objects that are intended for use with EJBwill transparentlyobtain a reference to the current transactions Coordinatorto register itself.

    Transactional vs Recoverable Objects

    OTSdistinguishes transactional and recoverable objects. This distinction isrelevant to EJB. While the full definition of these types is rather extensive inthe CORBAservices OTS Specification, it essentially means that recoverableobjects have a commit()and rollback()method, allowing the transaction todirectly manipulate their state or behavior. A transactional object does nothave these methods, and cannot be influenced by the transaction. However, atransactional object is an object that has a transaction associated with it, so thatrecoverable objects (or Resources) that are allocated will be associated withthe transactional objects current transaction.

    An enterprise bean is a good example of a transactional object. The container

    will maintain a transaction on behalf of the bean. Any recoverable objects thatare allocated by the bean are transparently placed into the current transactionwith the help of the container. The bean does not have a commit()orrollback()method, and so the transaction cannot manipulate the beandirectly. It doesnt really make sense to make a bean a recoverable Resourcesince this would require additional work on the part of the bean developer forevery bean written, and enterprise beans rarely have internal state that shoulddirectly affect the outcome of a transaction. They function better as managersof recoverable objects, letting the recoverable objects do the work.

    Note that a bean can vote to roll back a transaction prior to the containerattempting a commit or rollback. The rollback_only()method in theCoordinatoris provided to the bean in the EJBContextassetRollbackOnly()so that the bean can flag the transaction as requiring arollback when the time comes to terminate the transaction.

    A bean can still be told of the outcome of a transaction through theSessionSynchronizationinterface.

    Specifying Transaction Controls in the Deployment Descriptor

    The deployment descriptor for a bean contains an array ofControlDescriptorobjects. Each ControlDescriptordescribes, among

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 31

  • 8/12/2019 Ejb Developers Guide

    32/38

    other things, the transaction control that should be associated with thatmethod.

    The bean developer specifies the transaction controls for the methods in thebean. The deployer generally should not change these values without detailedknowledge of the transaction-related behavior of the method.

    The following six transaction controls are integer constants defined in theControlDescriptorclass. Aside from the methods of this class, there are noother APIs that access this information. The bean itself does not get access toits transaction controls for its methods.

    The container will read these control values to maintain the appropriatetransactional behavior for the bean.

    TX_NOT_SUPPORTED

    TX_SUPPORTS

    TX_REQUIRED

    TX_REQUIRES_NEW

    TX_MANDATORY

    TX_BEAN_MANAGED

    You would apply the appropriate value to the ControlDescriptorfor yourbeans method typically through a vendor-provided tool for creatingdeployment descriptors.

    TX_NOT_SUPPORTED

    This method should not run in a transactional context. If the executing threadis running within the transaction, the transaction will be suspended until thethread returns from the method.

    TX_SUPPORTS

    While a transaction is not required for this method, the thread may have anactive transaction when running this method.

    TX_REQUIRED

    This method must be run within in transaction. If the thread already has atransaction, the thread is allowed to enter the method. If the thread does nothave a transaction, the container will start one on behalf of the thread, allowthe thread to enter, and terminate the transaction once the thread returns.Normally the transaction is committed. If the thread invoked thesetRollbackOnly()method, the container will perform a rollback instead.

    TX_REQUIRES_NEW

    Regardless of whether or not the thread has a transaction, the container willcreate a new transaction for the duration of this method. When the threadreturns, the container will either commit or roll back the transaction. If thethread already had a transaction underway, it would be suspended until afterthe thread returned and the methods transaction was terminated.

    Version 1.4.1

    32 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    33/38

    TX_MANDATORY

    The thread must already be in a transaction when attempting to call thismethod. If the thread does not have a transaction, the container will throw anexception.

    TX_BEAN_MANAGED

    This control is somewhat different from the previous controls. A method withthis control is stating that the container should not play any part in transactionmanagement on the part of the method. Instead, the method is going to createand terminate its own transaction through a special interface that is accessibleonly for methods with this transaction control. This control will be covered inmore detail in a later section.

    JTS -Java Transaction Service

    TheJTSis actually not a transaction service, but an interface to an underlyingtransaction service provider.JTSis very simple, consisting of one interface an

    several exceptions. It is apparent by looking at its list of exceptions that it wasmodeled to work with OTS, although it could be used as an interface to othertransaction services also.

    For beans that declare their transaction control as bean-managed, the bean canget access to the transaction service through this interface. It can also be usedfor vendors that provide support for client-demarcated transactions.

    Here is the interface definition for UserTransaction:

    public interface javax.jts.UserTransaction {

    public void begin() throws

    IllegalStateException;

    public void commit() throws

    TransactionRolledBackException,

    HeuristicMixedException,

    HeuristicRollbackException,

    SecurityException,

    IllegalStateException;

    public void rollback() throws

    SecurityException,

    IllegalStateException;

    public void setRollbackOnly() throws

    IllegalStateException;

    public void setTransactionTimeout(int seconds);

    public int getStatus();

    // STATUS_ACTIVE, STATUS_COMMITTING,

    // STATUS_COMMITTED, STATUS_MARKED_ROLLBACK

    // STATUS_NO_TRANSACTION, STATUS_PREPARED

    // STATUS_PREPARING, STATUS_ROLLEDBACK

    // STATUS_ROLLING_BACK, STATUS_UNKNOWN

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 33

  • 8/12/2019 Ejb Developers Guide

    34/38

    }

    Bean-Managed Transactions

    A bean can get access to the transaction service provided the bean is declaredwith a transaction control of TX_BEAN_MANAGED. While transaction controls

    apply to individual methods, this control can only be applied to the entirebean. The ability of the bean to access the transaction service cannot beselectively applied to only certain methods of the bean.

    Therefore, it is an error for one method of the bean to declare the transactioncontrol of TX_BEAN_MANAGEDwhile another method declares a differenttransaction control. The vendors installation tool should detect this andreport an error.

    The bean gets access to the transaction service through the SessionContextor EntityContextprovided to bean initialization as the argument tosetSessionContext()or setEntityContext(), respectively. Each of theseinterfaces subclasses from EJBContext. The definition of EJBContextis asfollows:

    public interface javax.ejb.EJBContext {

    public Identity getCallerIdentity();

    public boolean isCallerInRole(Identity other);

    public EJBHome getEJBHome();

    public Properties getEnvironment();

    public UserTransaction getUserTransaction() throws

    IllegalStateException;

    public boolean getRollbackOnly();

    public void setRollbackOnly();

    }

    Once the bean obtains a UserTransactionreference, it can use the referenceto manage its own transactions.

    For stateful session beans, a method in the bean can create a transaction andreturn without terminating the transaction. Upon a subsequent call to one ofthe methods of the bean, the container will detect that a bean-createdtransaction is still in effect, and if the transaction being carried by the callingthread is the same transaction, the container will allow the thread to re-enterthe bean. If the bean is in a transaction and a thread carrying a differenttransaction context attempts to enter the bean, the container will block thethread until the beans transaction terminates. If the bean is not in atransaction when a thread attempts to enter the bean, and the thread iscarrying a transaction of its own, the container will suspend the threads

    current transaction and allow the thread to enter. The threads originaltransaction is restored once the thread leaves the method, but any transactioncreated by method is not terminated by the container.

    For both stateless session beans and entity beans, the beans method is notallowed to return with its transaction still active. The container should catchthis and throw an exception.

    Leaving a transaction active across method calls is stateful, and is not allowedfor stateless session beans. For similar reasons, entity beans are also not

    Version 1.4.1

    34 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    35/38

    allowed to maintain an open transaction state across method calls when thebean has declared the TX_BEAN_MANAGEDtransaction control.

    Session Synchronization Interface

    A session bean, stateless or stateful, is allowed to access a database, and can

    participate in transactions. To assist the bean in performing its work in atransaction, the bean developer can have the bean implement thejavax.ejb.SessionSynchronizationinterface.

    This interface is automatically detected by the container, and the containerwill use the methods in the interface as callbacks to keep the bean informedabout the state of the transaction.

    Entity beans do not support this interface. Since entity beans are implicitlytransaction-aware, the container uses different semantics for controlling anentity bean while it is within a transaction.

    The SessionSynchronizationinterface is defined as follows:

    public interface javax.ejb.SessionSynchronization {

    public void afterBegin() throws RemoteException;

    public void beforeCompletion() throws RemoteException;

    public void afterCompletion(boolean yn) throws

    RemoteException;

    }

    A transaction does not actually belong to a particular bean instance. A threadof execution creates a transaction, either in the client or in the container, andcarries its transaction with it when executes the code in the bean. If a threadthat has a transaction context is about to enter a session bean, the containerfirst invokes its afterBegin()method. The bean can record the fact that allbusiness method calls are running within a transaction, and subsequently

    allow certain transactional operations to execute. It would similarly rejectrequests to perform transactional operations if its internal flag indicated thatthis thread was not running within a transaction.

    The bean would continue to assume that its business method calls are part of atransaction until the afterCompletion()method is called. It wouldpresumably clear its internal flag indicating that subsequent requests thatrequire transactions should be rejected.

    If a thread that carries a transaction context attempts to enter a bean that isalready a part of another transaction, the container will block the entry untilthe previous transaction either commits or rolls back and theafterCompletion()method is called, allowing the bean to restore its state.

    The container is responsible for providing these behaviors.The beforeCompletion()method will be called on all session beans that area part of a particular transaction when the container realizes that it is about toattempt to commit the transaction. This gives the bean the opportunity tofinish its transactional operations, such as flushing any remaining data to thedatabase, before the transaction is committed. If the container realizes it isabout to perform a rollback instead, the beforeCompletion()method willnot be called, since it is pointless to flush data in a transaction where thetransaction is going to be rolled back, anyway.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 35

  • 8/12/2019 Ejb Developers Guide

    36/38

    The afterCompletion()method is called after the transaction is eithercommitted or rolled back to inform the bean about the final outcome of itstransactional operations. It can use this information to update its internalstate, but it should not use it to try to maintain any internal transactions it maybe trying to maintain. While it is possible for a session bean to create, commit,and roll back its own transactions, it is generally discouraged. The

    SessionSynchronizationinterface does not provide the capability offunctionally merging outer transactions with an inner transaction beingmaintained directly by the session bean.

    A session bean that implements this interface implies that it is maintainingstate across method calls. Specifically, the implication is that between the callsto afterBegin()and afterCompletion()the bean is within a transaction.Therefore, it is an error for a bean to implement theSessionSynchronizationinterface and be declared as stateless in itsdeployment descriptor. The vendors installation tool should catch this andreport an error.

    Stateless session beans can participate in transactions, but they cannotimplement this interface. The transaction could be TX_BEAN_MANAGED, or the

    container could start and commit the transaction upon entry to and returnfrom the method. The container should not allow a thread with an existingtransaction to enter the method, since the stateless beans method would notknow if the executing thread were running in the context of a transaction ornot.

    One way around this would be to have the container suspend an existingtransaction, forcing the method to always assume that the thread is notrunning the method in a transactional context.

    Stateful session beans can also participate in a transaction withoutimplementing this interface. However, the deployment descriptor would haveto be configured carefully so that the business methods always execute in the

    correct transaction state. The bean would not have the benefit of beinginformed of its transaction state through this interface.

    Taking Part in Transactions

    The EJBContextinterface was illustrated in a previous section. In thatinterface were two methods:

    public boolean getRollbackOnly();

    public void setRollbackOnly();

    These methods can be used by any bean, not just beans that declare theirtransaction control as bean-managed. In fact, beans that manage their owntransactions would not use these methods, since these methods are used tocommunicate transaction status to an outside transaction manager.

    When a bean calls setRollbackOnly()it is requesting to the transactionmanager that when it comes time to terminate the current transaction that thetransaction be rolled back. It gives beans a vote in the outcome of thetransactions in which they participate. These methods also exist in theUserTransaction interface, but since most beans will not have access to thisinterface, these methods must be provided to the bean directly in theEJBContext. Note that this method does not initiate a rollback, it simply sets a

    Version 1.4.1

    36 Copyright 1999 Nova Laboratories - Reproduction Prohibited

  • 8/12/2019 Ejb Developers Guide

    37/38

    flag that the transaction should be rolled back when the transaction isterminated.

    Unlike JavaBeans property setter methods, this one does not take a booleanvalue as an argument. The method is designed this way deliberately so that abean cannot revert the rollback request of another bean.

    A bean may wish to use the getRollbackOnly()method to check the currentstatus of the transaction. If another bean has already flagged the transactionfor rollback, the calling bean could presumably decide not to performintensive operations, such as database updates, that would be reverted oncethe transaction were terminated.

    Client-Demarcated Transactions

    While not a requirement for EJBvendors, a server vendor may decide toprovide a class that can be used by the client to directly access the transactionmanager. A client may wish to do this if it were necessary to invoke beans intwo different servers in the same context. Of course, each beans deployment

    descriptor would have to allow this behavior. The client could create atransaction and then invoke the business methods in two different beans ontwo different servers, passing the transaction context as part of the call. Oncethe calls were completed, the client would presumably terminate thetransaction. The stubs and skeletons generated by the container vendor wouldhave to support the implicit passing of a transaction context for this to work.

    Here is a possible example:

    Current current = new Current();

    current.setServiceProvider(txMgrURL);

    current.create();

    current.begin();

    remRef1.doSomeWork();

    remRef2.doMoreWork();

    current.commit();

    Transaction Management of Database Operations

    It is certainly desirable for a bean to be able to useJDBC to createconnections to databases and to perform work on that connection. However,to fit into the EJBmodel of having the container manage the beanstransaction, the connection must not use the auto-commit feature, and thebean should not attempt a commit or rollback on the connection.

    Presumably the container is the one that should determine if all transactionalbehavior executed within this transaction should be committed or rolled back.

    A good question at this point is how the container could see and manage adatabase connection created internally by the beans method. Although notstated explicitly in the Specification, enterprise beans should only useJDBCdrivers that were intended for use with EJB. Upon creation of a databaseconnection, these drivers will transparently register the connection with theexecuting threads current transaction. Later when the container decides toterminate the transaction, the database connection will be automaticallyterminated with it.

    Developers Guide to Understanding Enterprise JavaBeans

    Copyright 1999 Nova Laboratories - Reproduction Prohibited 37

  • 8/12/2019 Ejb Developers Guide

    38/38

    In OTSterms, the database connection is a recoverable Resourcethat isimplicitly managed by the transaction service with the help of the container.

    While it is possible to useJDBCdrivers that are not transaction-aware in thissense, the developer should be aware that any work done on this databaseconnection is not a part of the beans transaction, and the developer must besure to terminate the database connections transaction prior to returning fromthe method. Trying to use the SessionSynchronizationinterface tofunctionally merge the database connections transaction with the beanstransaction is unreliable and should not be attempted.

    Distributed Transaction Support

    A distributed transaction would be needed in the following cases:

    a client using client-demarcated transactions that creates and transactionand calls a method in one or more beans on one or more servers

    a beans method that invokes a method in another enterprise bean onanother server

    For this to work the vendor must generate stubs and skeletons for theEJBObject that will implicitly obtain the current transaction context and sendit in the method call to the remote bean. The skeleton for the remote beansEJBObject must apply this transaction context when delegating the businessmethod call to the bean.

    Version 1.4.1