m4_ejb

Upload: sandhu554

Post on 30-May-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 M4_EJB

    1/96

    Enterprise Java BeansEnterprise Java Beans

    Technology ConsultingTechnology Consulting

    PramatiPramatiTechnologiesTechnologies

  • 8/9/2019 M4_EJB

    2/96

    Agenda

    What is an EJBWhat is an EJB

    Bean BasicsBean Basics

    Component ContractComponent Contract

    Bean VarietiesBean Varieties

    Session Beans

    Entity Beans

    Message Driven Beans

  • 8/9/2019 M4_EJB

    3/96

    What is an EJB ?

  • 8/9/2019 M4_EJB

    4/96

    Bean is a component

    A server-side componentA server-side component

    Contains business logic that operates on some temporaryContains business logic that operates on some temporarydata or permanent databasedata or permanent database

    Is customizable to the target environmentIs customizable to the target environment

    Is re-usableIs re-usable

    Is truly platform-independentIs truly platform-independent

  • 8/9/2019 M4_EJB

    5/96

    A Typical Bean at Work

    Account Bean

    open ()

    deposit ()

    withdraw ()balance ()

    close ()

    Name

    Address

    Amount

    open ()

    deposit ()

    withdraw ()balance ()

    close ()

    Name

    Address

    Amount

    Client

    Client

    Database

  • 8/9/2019 M4_EJB

    6/96

    So, what is an EJB?

    Ready-to-use Java componentReady-to-use Java component Being Java implies portability, inter-operability

    Can be assembled into a distributed multi-tier applicationCan be assembled into a distributed multi-tier application

    Handles threading, transactionsHandles threading, transactions Manages state and resourcesManages state and resources

    Simplifies the development of complex enterpriseSimplifies the development of complex enterpriseapplicationsapplications

  • 8/9/2019 M4_EJB

    7/96

    EJB dumbs down complexity

    App

    lica

    tioncom

    plex

    ity Corba, COM

    EJB

    state mgmt

    distributed txn

    load balancing

    thread

    concurrencysecurity

    single user

    shared db

    Componentization

    Multi-tier architecture

    Desktop Network Web Large scale enterprise apps

  • 8/9/2019 M4_EJB

    8/96

    Where EJB fits in Multi-tier

    Presentation ObjectsPresentation Objects

    Business Logic ObjectsBusiness Logic Objects

    Data ObjectsData Objects

    ClientClient

  • 8/9/2019 M4_EJB

    9/96

    Benefits

    Pure Java implies portabilityPure Java implies portability

    exchange components without giving away the source

    Provides interoperabilityProvides interoperability

    assemble components from anywhere, can all work together

  • 8/9/2019 M4_EJB

    10/96

    Operational Benefits from EJB

    Transaction management serviceTransaction management service

    Distributed Transaction supportDistributed Transaction support

    PortabilityPortability

    ScalabilityScalability

    Integration with CORBA possibleIntegration with CORBA possible

    Support from multiple vendorsSupport from multiple vendors

  • 8/9/2019 M4_EJB

    11/96

    What Does EJB Really Define?

    Component architectureComponent architecture

    Specification to write components using JavaSpecification to write components using Java

    Specification to component server developersSpecification to component server developers

    Contract between developer roles in a components-basedContract between developer roles in a components-basedapplication projectapplication project

    The basis of components used in distributed transaction-

    oriented enterprise applications

  • 8/9/2019 M4_EJB

    12/96

    The Componentized Application

    Application now consists of several re-usable componentsApplication now consists of several re-usable components

    InstancesInstances of components created at run-time for a clientof components created at run-time for a client

    Common object for all instances of the component, usuallyCommon object for all instances of the component, usuallycalled the Factory Objectcalled the Factory Object

    EJB calls it Home Object

    Common place where client can locate thisCommon place where client can locate this Home ObjectHome Object

    Objects located from a remote client throughObjects located from a remote client through JNDIJNDI (Java(Java

    Naming and Directory Interface) serviceNaming and Directory Interface) service

  • 8/9/2019 M4_EJB

    13/96

    Application Server provides

    JNDI based naming serviceJNDI based naming service

    Implementation of Bean, Home and RemoteImplementation of Bean, Home and Remote

    Complete Life Cycle ManagementComplete Life Cycle Management

    Resource pooling - beans, db connections, threads...Resource pooling - beans, db connections, threads...

    Object persistenceObject persistence

    Transaction managementTransaction management

    Secured access to beansSecured access to beans

    Scalability and availabilityScalability and availability

  • 8/9/2019 M4_EJB

    14/96

    EJB: Core of J2EE Architecture

    J2EE ServerJ2EE Server

    EJB

    Container

    EJB

    Container

    Web

    Container

    JSP

    Servlets

    Java

    client

    BeansBeans

    rmiHTML

    client

    http

    Business logicBusiness logic

    EJB Component

    server

    EJB Component

    server

  • 8/9/2019 M4_EJB

    15/96

    The Architecture Scenario

    Create individual business and web componentsCreate individual business and web components

    Assemble these components into an applicationAssemble these components into an application

    Deploy application on an application serverDeploy application on an application server

    Run application on target environmentRun application on target environment

    Bean ProviderBean Provider

    AssemblerAssembler

    Server ProviderServer Provider

    Container ProviderContainer Provider

    DeployerDeployer

    Application

    Responsibilities

    Application

    Responsibilities

    Appointed forResponsibilitiesAppointed forResponsibilities

    AdministratorAdministrator

  • 8/9/2019 M4_EJB

    16/96

    EJB Architecture Roles Six roles in application development and deployment lifeSix roles in application development and deployment life

    cyclecycle

    Bean Provider

    Application Assembler

    Server Provider

    Container Provider

    Deployer

    System Administrator

    Each role performed by a different partyEach role performed by a different party Product of one role compatible with anotherProduct of one role compatible with another

  • 8/9/2019 M4_EJB

    17/96

    DeployerDeployerSystem

    Administrator

    System

    Administrator

    Server

    Provider

    Server

    Provider

    AssemblerAssemblerBean

    Developer

    Bean

    Developer

    Container

    Provider

    Container

    Provider

    How the Roles Collaborate

    Create Assemble Deploy

  • 8/9/2019 M4_EJB

    18/96

    Bean Basics

  • 8/9/2019 M4_EJB

    19/96

    Creating the Bean Instance

    Look up for the Home Object through JNDILook up for the Home Object through JNDI Get the referenceGet the reference

    CallCall create() methodcreate() method

    The server generates the code for remote access usingThe server generates the code for remote access using RMIRMI(Remote Method Invocation).(Remote Method Invocation).

    The RMI code in the form of stub and skeleton:The RMI code in the form of stub and skeleton:

    establishes connection,

    marshals/unmarshals

    places remote method calls

  • 8/9/2019 M4_EJB

    20/96

    ...Bean Instance

    Client

    Component ServerComponent Server

    Name ServerName Server

    Home

    Object Client calls create()

    Bean places reference to

    Home Object under JNDI

    Naming service

    Client locates Home

    Object

    Bean Instance created Bean

  • 8/9/2019 M4_EJB

    21/96

    Using the Component

    Client

    Component ServerComponent Server

    Remote Object

    Client gets reference to

    EJB Object after create()

    Client calls business

    method on EJB ObjectBean

    EJB Object delegates to

    bean instance

    Writing business methods is the

    bean developers main work

    All bean methods are exposed asremote accessible functions by

    the EJB Object

    Writing business methods is the

    bean developers main work

    All bean methods are exposed asremote accessible functions by

    the EJB Object

    Business

    Methods

  • 8/9/2019 M4_EJB

    22/96

    Locating a Component

    Client

    Component ServerComponent Server

    Remote Object

    Bean

    Home Object finds the

    Bean creates aninstance

    Client calls find() method

    on Home Object

    Returns reference to

    the EJB Object of

    new Bean instance

    Find method revives instances of

    bean at a point after creation

    Bean writer writes Find methods

    Find method is exposed through

    the Home Object

    Find method revives instances of

    bean at a point after creation

    Bean writer writes Find methods Find method is exposed through

    the Home Object

  • 8/9/2019 M4_EJB

    23/96

    A Typical Bean Application

    Client

    Component ServerComponent Server

    Account1

    Account2

    Teller

    Session Bean

    Entity Bean

    A typical application requires a collection of bean classes deployed on the server.

    Beans could be of three types: Session Beans - that represent process objects

    Entity Beans - that represent data objects Message Driven Beans that act as message consumers

  • 8/9/2019 M4_EJB

    24/96

    Benefits of Beans - A Recall

    Less programming complexityLess programming complexity

    Focus on business logic and plumbing code is availableFocus on business logic and plumbing code is available

    Enterprise Level Services like Transaction, Security,Enterprise Level Services like Transaction, Security,

    Naming availableNaming available Container Managed PersistenceContainer Managed Persistence

    Server Managing precious resourcesServer Managing precious resources

    Very high level of reuseVery high level of reuse PortabilityPortability

  • 8/9/2019 M4_EJB

    25/96

    Component Contract

  • 8/9/2019 M4_EJB

    26/96

    Container: The Host on the Server

    Hosts multiple EJBsHosts multiple EJBs

    Provides life-cycle management for EJB create, locate, remove,Provides life-cycle management for EJB create, locate, remove,

    remote method callsremote method calls Provides high-performance in handling large pool of bean instancesProvides high-performance in handling large pool of bean instances

    ledgerledgeraccount1account1

    tellertelleraccount2account2

    EJB

    Container

    Beans

    Naming Txn Security

    interfaces

    EJB

    Server

  • 8/9/2019 M4_EJB

    27/96

    Client, Container & Bean Work... Component Server hosts the containerComponent Server hosts the container

    The Container hosts the beans and provides infrastructural support forThe Container hosts the beans and provides infrastructural support for

    the beans to functionthe beans to function

    Beans can be deployed in any container that conforms with EJBBeans can be deployed in any container that conforms with EJB

    specificationsspecifications

    Bean instance created, managed at run-time by the containerBean instance created, managed at run-time by the container

    Container mediates client access to the EJBContainer mediates client access to the EJB

    These activities are enabled by non-negotiable contracts

    among the client, component and container

  • 8/9/2019 M4_EJB

    28/96

    Via Contracts Client-view contractClient-view contract

    Component contractComponent contract

    EJB-jar fileEJB-jar file

    Component ServerComponent Server

    ContainerContainer

    Bean InstanceBean Instance

    Component

    Contract

    Component

    Contract

    ClientClientClient

    View

    Contract

    Client

    View

    Contract

    Bean class files, interfacesBean class files, interfaces

    Deployment descriptorDeployment descriptorEJB-jarEJB-jar

  • 8/9/2019 M4_EJB

    29/96

    Client-view contract

    Contract between client and containerContract between client and container Uniform application development model forUniform application development model for

    greater re-use of componentsgreater re-use of components

    View sharing by local and remote programsView sharing by local and remote programs

    The Client can be:The Client can be:

    another EJB deployed in same or another container

    a Java program, an applet or a Servlet

    mapped to non-Java clients like CORBA clients

    Home InterfaceHome Interface

    Remote InterfaceRemote Interface

    Object IdentityObject Identity

    Metadata InterfaceMetadata Interface

    Container HandleContainer Handle

  • 8/9/2019 M4_EJB

    30/96

    Component contract

    Between an EJB and the container it is hosted byBetween an EJB and the container it is hosted by This contract needs responsibilities to be shared by:This contract needs responsibilities to be shared by:

    the bean provider

    the container provider

    Container

    providers

    responsibilitiesBean

    providers

    responsibilities

  • 8/9/2019 M4_EJB

    31/96

    Bean providers responsibility

    Implement business methods in the beanImplement business methods in the bean ImplementImplement ejbCreate, ejbPostCreateejbCreate, ejbPostCreate andand ejbRemoveejbRemove

    methods, andmethods, and ejbFindejbFindmethod (in the case of bean managedmethod (in the case of bean managedpersistence)persistence)

    Define home and remote interfaces of the beanDefine home and remote interfaces of the bean

    Implement container callbacks defined in theImplement container callbacks defined in thejavax.ejb.Sessionjavax.ejb.Session bean interfacebean interface

    optionally thejavax.ejb.SessionSynchronization interface

    ......

  • 8/9/2019 M4_EJB

    32/96

    responsibility

    Implement container callbacks defined inImplement container callbacks defined injavax.ejb.EntityBeanjavax.ejb.EntityBean interfaces for entitiesinterfaces for entities

    Avoid programming practices that interfere with containersAvoid programming practices that interfere with containers

    runtime management of bean instancesruntime management of bean instances

  • 8/9/2019 M4_EJB

    33/96

  • 8/9/2019 M4_EJB

    34/96

  • 8/9/2019 M4_EJB

    35/96

    Ejb-jar file

    Standard format used by EJB tools for packagingStandard format used by EJB tools for packaging(assembling) beans along with declarative information(assembling) beans along with declarative information

    Contract between bean provider and application assembler,Contract between bean provider and application assembler,

    and between application assembler and application deployerand between application assembler and application deployer

    The file includes:The file includes:

    Java class files of the beans along with their remote and home

    interfaces

    XML deployment descriptor that provides both structural and

    application assembly information about the beans

  • 8/9/2019 M4_EJB

    36/96

    Finally, the Big Picture

    Application

    ServerEJB

    Container

    Databases

    /Other

    EnterpriseSystems

    HTML/Java

    Client

    Create, find,

    remove methods

    Create, find,

    remove methods

    Business methodsBusiness methods

    Bean

  • 8/9/2019 M4_EJB

    37/96

    Bean Varieties

  • 8/9/2019 M4_EJB

    38/96

    Three Types of BeansSession Beans - Short lived and last during a sessionSession Beans - Short lived and last during a session

    Entity Beans - Long lived and persist throughoutEntity Beans - Long lived and persist throughout

    Message Driven Beans Asynchronous Message ConsumersMessage Driven Beans Asynchronous Message Consumers

    Session A Session C

    Session B

    Session D

  • 8/9/2019 M4_EJB

    39/96

    Session Beans

  • 8/9/2019 M4_EJB

    40/96

    What is a Session Bean?

    A session object is a non-persistent object that implements someA session object is a non-persistent object that implements somebusiness logic running on the server.business logic running on the server.

    Executes on behalf of a single client.Executes on behalf of a single client.

    Can be transaction aware.Can be transaction aware.

    Does not represent directly shared data in the database, although it mayDoes not represent directly shared data in the database, although it mayaccess and update such data.access and update such data.

    Is relatively short-lived.Is relatively short-lived.

    Is removed when the EJB container crashes. The client has to re-Is removed when the EJB container crashes. The client has to re-

    establish a new session object to continue computationestablish a new session object to continue computation

  • 8/9/2019 M4_EJB

    41/96

    Types of Session Beans

    There are two types of session beans:There are two types of session beans: Stateless

    Stateful

  • 8/9/2019 M4_EJB

    42/96

    Clients view of a Session Bean

    A client accesses a session object through the session beansA client accesses a session object through the session beansRemote Interface or Local Interface.Remote Interface or Local Interface.

    Each session object has an identity which, in general, doesEach session object has an identity which, in general, does

    not survive a crashnot survive a crash

  • 8/9/2019 M4_EJB

    43/96

    Locating a session beans home interface

    Remote Home interfaceRemote Home interfaceContext initialContext = new InitialContext();Context initialContext = new InitialContext();

    CartHome cartHome = (CartHome)CartHome cartHome = (CartHome)

    javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(java:comp/env/javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(java:comp/env/

    ejb/cart), CartHome.class);ejb/cart), CartHome.class);

    Local Home InterfaceLocal Home Interface

    Context initialContext = new InitialContext();Context initialContext = new InitialContext();

    CartHome cartHome = (CartHome)CartHome cartHome = (CartHome)

    initialContext.lookup(java:comp/env/ejb/cart);initialContext.lookup(java:comp/env/ejb/cart);

  • 8/9/2019 M4_EJB

    44/96

    Session Beans Local Home Interface

    object that implements is called a session EJBLocalHomeobject that implements is called a session EJBLocalHomeobject.object.

    Create a new session object.Create a new session object.

    Remove a session object.Remove a session object.

  • 8/9/2019 M4_EJB

    45/96

    Session Beans Remote Home Interface

    object that implements is called a session EJBHome object.object that implements is called a session EJBHome object.

    Create a session objectCreate a session object

    Remove a session objectRemove a session object

  • 8/9/2019 M4_EJB

    46/96

    Session Beans Local Interface

    Instances of a session beans remote interface are calledInstances of a session beans remote interface are calledsessionsession EJBObjecEJBObjectsts

    business logic methods of the object.business logic methods of the object.

  • 8/9/2019 M4_EJB

    47/96

    Session Beans Local Home Interface

    instances of a session beans local interface are calledinstances of a session beans local interface are calledsessionsession EJBLocalObjectEJBLocalObjectss

    business logic methods of the objectbusiness logic methods of the object

  • 8/9/2019 M4_EJB

    48/96

  • 8/9/2019 M4_EJB

    49/96

    EJBObject or EJBLocalObject

    Client never directly accesses instances of a Session BeansClient never directly accesses instances of a Session Beansclassclass

    Client uses Session Beans Remote Interface or RemoteClient uses Session Beans Remote Interface or Remote

    Home Interface to access its instanceHome Interface to access its instance

    The class that implements the Session Beans RemoteThe class that implements the Session Beans Remote

    Interface or Remote Home Interface is provided by theInterface or Remote Home Interface is provided by the

    container.container.

  • 8/9/2019 M4_EJB

    50/96

    Session Object Identity

    Session Objects are meant to be private resources of theSession Objects are meant to be private resources of theclient that created themclient that created them

    Session Objects, from the clients perspective, appearSession Objects, from the clients perspective, appear

    anonymousanonymous

    Session Beans Home Interface must not define finderSession Beans Home Interface must not define finder

    methodsmethods

  • 8/9/2019 M4_EJB

    51/96

    Session Object Identity

    Stateful Session BeansStateful Session Beans

    A stateful session object has a unique identity that is assigned by the

    container at the time of creation

    A client can determine if two object references refer to the same session

    object by invoking the isIdentical(EJBObject otherEJBObject) method onone of the references

    Stateless Session BeansStateless Session Beans

    All session objects of the same stateless session bean, within the same home

    have the same object identity assigned by the container

    isIdentical(EJBObject otherEJBObject) method always returns true

  • 8/9/2019 M4_EJB

    52/96

    LifeCycle of a Session Object

  • 8/9/2019 M4_EJB

    53/96

  • 8/9/2019 M4_EJB

    54/96

    Activation and Passivation

    Session bean container may temporarily transfer state of anSession bean container may temporarily transfer state of anidle stateful session bean instance to some form ofidle stateful session bean instance to some form of

    secondary storagesecondary storage

    Transfer from working set to secondary storage is calledTransfer from working set to secondary storage is called

    instance passivationinstance passivation

    Transfer back from the secondary storage to the instanceTransfer back from the secondary storage to the instance

    variables is calledvariables is called instance activationinstance activation

  • 8/9/2019 M4_EJB

    55/96

    Stateless Session Bean State Diagram

  • 8/9/2019 M4_EJB

    56/96

    Stateful Session Bean State Diagram

  • 8/9/2019 M4_EJB

    57/96

    Entity Beans

  • 8/9/2019 M4_EJB

    58/96

    Long Live Entity Beans!

    A component that represents an object-oriented view of some entitiesA component that represents an object-oriented view of some entitiesstored in a persistent storage like a database or an enterprise application.stored in a persistent storage like a database or an enterprise application.

    From its creation until its destruction, an entity object lives in aFrom its creation until its destruction, an entity object lives in a

    container.container.

    Transparent to the client, the Container provides security, concurrency,Transparent to the client, the Container provides security, concurrency,

    transactions, persistence, and other services to support the Entity Beanstransactions, persistence, and other services to support the Entity Beans

    functioningfunctioning

    Container Managed Persistence versus Bean Managed Persistence

    Multiple clients can access an entity object concurrentlyMultiple clients can access an entity object concurrently

  • 8/9/2019 M4_EJB

    59/96

    ...Entity Beans!

    Container hosting the Entity Bean synchronizes access toContainer hosting the Entity Bean synchronizes access tothe entity objects state using transactionsthe entity objects state using transactions

    Each entity object has an identity which usually survives aEach entity object has an identity which usually survives atransaction crashtransaction crash

    Object identity is implemented by the container with helpObject identity is implemented by the container with helpfrom the enterprise bean classfrom the enterprise bean class

    Multiple enterprise beans can be deployed in a ContainerMultiple enterprise beans can be deployed in a Container

  • 8/9/2019 M4_EJB

    60/96

    Remote Clients

    Accesses an entity bean through the entity beans remoteAccesses an entity bean through the entity beans remoteand remote home interfacesand remote home interfaces

    Implements EJBObject and EJBHome InterfacesImplements EJBObject and EJBHome Interfaces

    Location IndependentLocation Independent

    Potentially Expensive, Network LatencyPotentially Expensive, Network Latency

    Useful for coarse grained component accessUseful for coarse grained component access

  • 8/9/2019 M4_EJB

    61/96

    Local Clients

    Local client is a client that is collocated with the entity beanLocal client is a client that is collocated with the entity beanand which may be tightly coupled to the bean.and which may be tightly coupled to the bean.

    Implements EJBLocalObject and EJBLocalHome InterfacesImplements EJBLocalObject and EJBLocalHome Interfaces

    Same JVMSame JVM

    Enterprise bean can-not be deployed on a node differentEnterprise bean can-not be deployed on a node different

    from that of its client - Restricts distribution of components.from that of its client - Restricts distribution of components.

    Better supports fine-grained component accessBetter supports fine-grained component access

  • 8/9/2019 M4_EJB

    62/96

  • 8/9/2019 M4_EJB

    63/96

    Entity Beans Remote Home Interface

    Container provides the implementation of the RemoteContainer provides the implementation of the RemoteHome Interface for each Entity Bean deployed in theHome Interface for each Entity Bean deployed in the

    containercontainer

    Container makes the Remote Home Interface of all EntityContainer makes the Remote Home Interface of all Entity

    Beans deployed in it accessible to Clients through JNDIBeans deployed in it accessible to Clients through JNDI

    The object that implements an Entity Beans Remote HomeThe object that implements an Entity Beans Remote Home

    Interface is called anInterface is called anEJBHomeEJBHome objectobject

  • 8/9/2019 M4_EJB

    64/96

    Entity Beans Remote Home Interface

    Create new entity objects within the homeCreate new entity objects within the home

    Find existing entity objects within the homeFind existing entity objects within the home

    Remove an entity object from the homeRemove an entity object from the home

  • 8/9/2019 M4_EJB

    65/96

    Create Methods

    Entity Beans Remote Home Interface can define multipleEntity Beans Remote Home Interface can define multiple

    create()create()

    methods, each defining a way of creating an entity objectmethods, each defining a way of creating an entity object

    Arguments ofArguments ofcreate()create() initialize the state of the entity objectinitialize the state of the entity object

    Return type of aReturn type of a create()create() method is Entity Beans Remote Interfacemethod is Entity Beans Remote Interface

    TheThe throwsthrows clause of everyclause of every create()create() method includes themethod includes thejava.rmi.RemoteExceptionjava.rmi.RemoteException andandjavax.ejb.CreateExceptionjavax.ejb.CreateException

  • 8/9/2019 M4_EJB

    66/96

    finderMethods

    Entity Beans Home Interface defines manyEntity Beans Home Interface defines many

    finderfinder

    methodsmethods

    Name of eachName of each finderfindermethod starts with the prefix findmethod starts with the prefix find

    Arguments of aArguments of afinderfindermethod are used by the Entity Beanmethod are used by the Entity Bean

    implementation to locate requested entity objectsimplementation to locate requested entity objects

    Return type of aReturn type of afinderfindermethod must be the Entity Beans Remotemethod must be the Entity Beans RemoteInterface, or a collection of Remote InterfacesInterface, or a collection of Remote Interfaces

    TheThe throwsthrows clause of everyclause of everyfinderfindermethod includes themethod includes the

    java.rmi.RemoteExceptionjava.rmi.RemoteException andandjavax.ejb.FinderExceptionjavax.ejb.FinderException

  • 8/9/2019 M4_EJB

    67/96

    Entity Beans Remote Interface

    Client accesses an entity object through Entity Beans Remote InterfaceClient accesses an entity object through Entity Beans Remote Interface

    Entity beans Remote Interface must extendEntity beans Remote Interface must extendjavax.ejb.EJBObjectjavax.ejb.EJBObject

    interfaceinterface

    Remote Interface defines business methods which are callable by clientsRemote Interface defines business methods which are callable by clients

    The container provides the implementation of the methods defined inThe container provides the implementation of the methods defined inthethejavax.ejb.EJBObjectjavax.ejb.EJBObjectinterfaceinterface

    Only business methods are delegated to the instances of the enterpriseOnly business methods are delegated to the instances of the enterprise

    bean classbean class

  • 8/9/2019 M4_EJB

    68/96

    Entity Objects Life Cycle

  • 8/9/2019 M4_EJB

    69/96

    Entity Beans Local Home Interface

    must extend themust extend the javax.ejb.EJBLocalHomejavax.ejb.EJBLocalHome interfaceinterface Each method must be one of the:Each method must be one of the:

    Create methods

    Find methods

    Home methods

  • 8/9/2019 M4_EJB

    70/96

    Entity Beans Local Interface

    Local client can access an entity object through the entity beans localLocal client can access an entity object through the entity beans local

    interface.interface.

    must extend themust extend the javax.ejb.EJBLocalObjectjavax.ejb.EJBLocalObject interface.interface.

    defines the business methods callable by local clients.defines the business methods callable by local clients.

  • 8/9/2019 M4_EJB

    71/96

    Persistence Management

    Data access protocol for transferring state of the entityData access protocol for transferring state of the entitybetween the Entity Bean instances and the database isbetween the Entity Bean instances and the database isreferred to as object persistencereferred to as object persistence

    There are two ways to manage this persistence during anThere are two ways to manage this persistence during anapplications lifetimeapplications lifetime

    Bean-managed

    Container-managed

  • 8/9/2019 M4_EJB

    72/96

    Bean Managed Persistence

    Entity Bean provider writes database access calls directlyEntity Bean provider writes database access calls directlyinto the enterprise bean classinto the enterprise bean class

  • 8/9/2019 M4_EJB

    73/96

    Container Managed Persistence

    Bean Provider need not write database calls in the beanBean Provider need not write database calls in the bean

    Container providers tools generate database access calls atContainer providers tools generate database access calls atdeployment timedeployment time

    Advantage:Advantage: Entity Bean can be mostly independent fromEntity Bean can be mostly independent from

    the data source in which the entity is storedthe data source in which the entity is stored Disadvantage:Disadvantage: Sophisticated tools are needed atSophisticated tools are needed at

    deployment time to map Entity Bean fields to data sourcedeployment time to map Entity Bean fields to data source

  • 8/9/2019 M4_EJB

    74/96

    Life Cycle of an Entity Bean Instance

    Q

  • 8/9/2019 M4_EJB

    75/96

    EJB QL

    Need for standardizing queriesNeed for standardizing queries Why not SQL?Why not SQL?

    EJB QL: EJB Query LanguageEJB QL: EJB Query Language

    Specification language Based on the CMP Data Model (Abstract Persistence Schema)

    Compiled to a target language: SQL

    EJB QL E l

  • 8/9/2019 M4_EJB

    76/96

    EJB QL Example

    SELECT OBJECT(l) From OrderBean o, in(o.lineItems) lSELECT OBJECT(l) From OrderBean o, in(o.lineItems) l

    SELECT l.LINEITEM_ID FROM LINEITEMEJBTABLE l, ORDEREJBTABLE oSELECT l.LINEITEM_ID FROM LINEITEMEJBTABLE l, ORDEREJBTABLE o

    WHERE (l.ORDER_ID = o.ORDER_ID )WHERE (l.ORDER_ID = o.ORDER_ID )

    SELECT OBJECT(o) FROM OrderBean o WHERE o.creditCard.expires = '03/05'"SELECT OBJECT(o) FROM OrderBean o WHERE o.creditCard.expires = '03/05'"

    SELECT o.ORDER_ID FROM CREDITCARDEJBTABLE a_1,SELECT o.ORDER_ID FROM CREDITCARDEJBTABLE a_1,

    ORDEREJBTABLE o WHERE ((a_1.EXPIRES='03/05' ANDORDEREJBTABLE o WHERE ((a_1.EXPIRES='03/05' AND

    o.CREDITCARD_ID = a_1.CREDITCARD_ID ))o.CREDITCARD_ID = a_1.CREDITCARD_ID ))

    EJB QL E l

  • 8/9/2019 M4_EJB

    77/96

    EJB QL Example

    SELECT c.addressSELECT c.address

    FROM CustomerBeanSchema cFROM CustomerBeanSchema c

    WHERE c.iD=?1 AND c.firstName=?2WHERE c.iD=?1 AND c.firstName=?2

    SELECT ADDRESS.IDSELECT ADDRESS.ID

    FROM ADDRESS, CUSTOMERFROM ADDRESS, CUSTOMER

    WHERE CUSTOMER.CUSTOMERID=?WHERE CUSTOMER.CUSTOMERID=?

    AND CUSTOMER.FIRSTNAME=?AND CUSTOMER.FIRSTNAME=?

    AND CUSTOMER.CUSTOMERID = ADDRESS.CUSTOMERIDAND CUSTOMER.CUSTOMERID = ADDRESS.CUSTOMERID

    EJB QL D l D i

  • 8/9/2019 M4_EJB

    78/96

    EJB QL: Deployment Descriptor

    Method finds large ordersMethod finds large orders

    findAllCustomersfindAllCustomers

    SELECT OBJECT(c) FROM CustomerBeanSchema cSELECT OBJECT(c) FROM CustomerBeanSchema c

    H B i M h d

  • 8/9/2019 M4_EJB

    79/96

    Home Business Methods

    Methods in the Home InterfaceMethods in the Home Interface

    Implementation provided by Bean Provider with matchingImplementation provided by Bean Provider with matching

    ejbHomeejbHome in the Beanin the Bean

    Exposed to the Client ViewExposed to the Client View

    Not specific to any Bean instanceNot specific to any Bean instance

  • 8/9/2019 M4_EJB

    80/96

  • 8/9/2019 M4_EJB

    81/96

    E l f EJB 2 0 CMP B

  • 8/9/2019 M4_EJB

    82/96

    Example of EJB 2.0 CMP Bean

    publicpublic abstractabstract class AccountBean implements EntityBean {class AccountBean implements EntityBean {

    ////Virtual FieldsVirtual Fields

    publicpublic abstractabstract long getAccount_number();long getAccount_number();

    publicpublic abstractabstract void setAccount_number(long account_number);void setAccount_number(long account_number);

    publicpublic abstractabstract java.lang.String getCustomer_name();java.lang.String getCustomer_name();

    publicpublic abstractabstract void setCustomer_name(String customer_name);void setCustomer_name(String customer_name);

    publicpublic abstractabstract double getBalance();double getBalance();

    publicpublic abstractabstract void setBalance(double balance);void setBalance(double balance);

    // Business Method// Business Method

    public void credit ( double amount ) {public void credit ( double amount ) {

    double balance =double balance = getBalance();getBalance();

    balance += amount;balance += amount;

    setBalance(balance);setBalance(balance);

    }}

    }}

  • 8/9/2019 M4_EJB

    83/96

    Abstract Schema : Deployment Descriptor

    CustomerBeanSchemaCustomerBeanSchema

    id of the customerid of the customer

    iDiD

    First name of the customerFirst name of the customer

    firstNamefirstName

    Last name of the customerLast name of the customer

    lastNamelastName

    iDiD

    C t i M d R l ti hi

  • 8/9/2019 M4_EJB

    84/96

    Container Managed Relationships

    Container Managed RelationshipsContainer Managed Relationships

    Bean-Bean, Bean-Dependent, Dependent-DependentBean-Bean, Bean-Dependent, Dependent-Dependent

    Defined using Abstract Accessor MethodsDefined using Abstract Accessor Methods

    Unidirectional or Bi-directionalUnidirectional or Bi-directional

    LineItem Product

    Student Course

    CardinalityCardinality

    One to One

    One to Many

    Many to One

    Many to Many

  • 8/9/2019 M4_EJB

    85/96

    E l E tit B P d t

  • 8/9/2019 M4_EJB

    86/96

    Example Entity Bean: Product

    public abstract OrderBean extends Entity Bean {public abstract OrderBean extends Entity Bean {

    // Virtual Fields // Virtual Fields

    public abstract Long getProductID();public abstract Long getProductID();

    public abstract void setProductID(Long orderID);public abstract void setProductID(Long orderID);

    // Virtual Fields // Virtual Fields

    public abstract String getProductCategory();public abstract String getProductCategory();

    public abstract void setProductCategory (String category);public abstract void setProductCategory (String category);

    // NO Relationship Fields// NO Relationship Fields

    }}

    Relationships: Deployment Descriptor

  • 8/9/2019 M4_EJB

    87/96

    Relationships: Deployment Descriptor

    ONE-TO-ONE: Customer and AddressONE-TO-ONE: Customer and Address

    Customer-AddressCustomer-Address

    customer has one addresss customer has one addresss

    oneone

    CustomerBeanCustomerBean

    addressaddress

    Address belong to the Customer Address belong to the Customer

    oneone

    AddressBeanAddressBean

  • 8/9/2019 M4_EJB

    88/96

    Message Driven Beans

    MDB: Whats the need ?

  • 8/9/2019 M4_EJB

    89/96

    MDB: Whats the need ?

    Interactions between client and Home, Remote Interfaces ofInteractions between client and Home, Remote Interfaces of

    session and entity beans is synchronoussession and entity beans is synchronous

    Request sentRequest sent Server Object respondsServer Object responds

    Leads to blockage till response occursLeads to blockage till response occurs

    EJB model does not allow creation of threads withinEJB model does not allow creation of threads within

    component codecomponent code

    Message Driven Beans (MDB)

  • 8/9/2019 M4_EJB

    90/96

    Message Driven Beans (MDB)

    Asynchronous message consumer.Asynchronous message consumer.

    Can consume messages from Topics and QueuesCan consume messages from Topics and Queues

    Invoked by the container on the arrival of a JMS message.Invoked by the container on the arrival of a JMS message.

    No conversational state. - all bean instances are equivalentNo conversational state. - all bean instances are equivalent

    when they are not involved in servicing a client message.when they are not involved in servicing a client message.

    Anonymous - No client-visible identityAnonymous - No client-visible identity

    No Home, Remote Interface - Not exposed to client viewNo Home, Remote Interface - Not exposed to client view

    Message Driven Beans

  • 8/9/2019 M4_EJB

    91/96

    Message Driven Beans

    GoalGoal Make developing an enterprise bean that is asynchronouslyMake developing an enterprise bean that is asynchronously

    invoked to handle the processing of incoming JMSinvoked to handle the processing of incoming JMS

    messages as simple as developing the same functionality inmessages as simple as developing the same functionality in

    any other JMS MessageListener.any other JMS MessageListener. To allow for the concurrent processing of a stream ofTo allow for the concurrent processing of a stream of

    messages by means of container-provided pooling ofmessages by means of container-provided pooling of

    message-driven bean instances.message-driven bean instances.

    Client View of MDBs

  • 8/9/2019 M4_EJB

    92/96

    Client View of MDBs

    The existence of a message-driven bean is completelyThe existence of a message-driven bean is completelyhidden behind the JMS destination for which the MDB ishidden behind the JMS destination for which the MDB is

    the message listener.the message listener.

    MethodMethod onMessageonMessage triggered by an incoming messagetriggered by an incoming message

  • 8/9/2019 M4_EJB

    93/96

    Responsibilities

  • 8/9/2019 M4_EJB

    94/96

    Responsibilities

    Bean ProviderBean Provider

    Provide MDB class

    ejbCreate()

    onMessage()

    ejbRemove()

    Container ProviderContainer Provider

    Generation of implementation classes

    Deployment of MDBs

    Transactions, security

    E l MDB A li ti

  • 8/9/2019 M4_EJB

    95/96

    Example MDB Application

  • 8/9/2019 M4_EJB

    96/96