Overview of Enterprise JavaBeans (EJB)

computerharpyΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

97 εμφανίσεις

Enterprise JavaBeans

1

Overview of

Enterprise JavaBeans (EJB)

Enterprise JavaBeans

2

Applications to Date


Web Applications (Servlets/JSPs)


Provided user interface


access to database


simple business logic


no transactions except at the database level; no distributed
transactions across business logic


Distributed Applications (RMI)


Distributed access to business logic


access to, but no direct support for database


limited transactions;limited security


We have to write a lot of ‘plumbing’ code

Enterprise JavaBeans

3

What didn’t we address ?


Component reusability


Security


Threading


Resource Management


Load
-
Balancing


Fault Tolerance (a little with activation)


Could someone else deploy your application?


Web application yes, RMI application probably not


Need web application capability for business logic


Enterprise JavaBeans

4

Paradigm Shift


We need to start thinking of applications as a set of
reusable components and some business logic that ties the
components together


Deployed in a re
-
usable environment that handles
middleware and deployment requirements

Enterprise JavaBeans

5

Components Vs. Objects


Usually larger
-
grained


Provide a complete capability


Credit Card Verification


Can be customized for deployment

Enterprise JavaBeans

6

Component Architectures


Client
-
Side


Applets


Java Beans (development components)


ActiveX


Server Side


Servlets


Enterprise Java Beans (EJB)


CORBA Components


Microsoft Distributed interNet Applications Architecture (DNA)

Enterprise JavaBeans

7

Component Transaction Monitors
(CTMs)


Sophisticated distributed object Application Servers


usually made up of web servers, ORBs, Messaging, Databases, Naming,
etc.


Hybrid of TP Monitors (e.g., CICS and Tuxedo)and ORBs (e.g.,
CORBA and RMI)


Provide infrastructure for managing transactions, object distribution,
concurrency, security, persistence, and resource management


the developer isn’t left “rolling their own”


the developer complies with the model and basically implements a lot of
callback event and declarative programming


Analogy: CD
-
player = CTM, CD = Server
-
side Component

Enterprise JavaBeans

8

Enterprise JavaBeans (EJBs)


Standard server
-
side component model for Java Enterprise
Applications


security


resource pooling


persistence


concurrency


transactional integrity


Has nothing to do with “JavaBeans”


JavaBeans designed for intra
-
process purposes


GUIs


non
-
visual widgets


Enterprise Java Beans (EJB) designed for inter
-
process purposes

Enterprise JavaBeans

9

EJBs (cont.)


Java


platform independence


“write once, run anywhere”


EJB components


platform/implementation independence


write once, run in any Application Server complying with the EJB
spec


J2EE reference implementation


IBM’s Websphere


BEA’s Weblogic Server and Weblogic Enterprise


JONAS


...


Enterprise JavaBeans

10

EJB Architecture


Interfaces and Classes


beans


entity bean


session bean


Stateless session bean


Stateful session bean


primary key (for entity beans)


home interface


remote interface (EJB Object)


Container


Application Server

Enterprise JavaBeans

11

Bean Types


Entity beans


models persistent state
-

this state is maintained through all method and
server invocations. Concurrent access


nouns of the domain


real world objects (e.g. Owner, Account, Transaction)


Session beans


models business process
-

this state will be lost between method invocations
(stateless session) or client sessions (stateful session)


manage tasks performed on behalf of a single client (e.g. Teller, Monthly
Statement)


contains the business processes in which to use entity beans


manages actions that may cross entity beans or go outside the concern of an
entity bean


e.g. Teller may authenticate the user and transfer funds between accounts


e.g. Statement may include transactions from multiple accounts

Enterprise JavaBeans

12

Bean Usages


Entity beans


model state maintained across all client interactions


represent a row of data in a database


Session beans


model business process being performed by a single client
involving one or more entity beans


it extends the actions of the client into the server


simplifies the actions programmed by the client


limits the number of distributed calls required between the client and
the entity beans


limits the number of stubs that have to be loaded by the client


are not persisted to a database

Enterprise JavaBeans

13

Stateful and Stateless session beans


Stateful session bean


maintain the conversational state between a client and the session
bean


may be serialized out and passivated to conserve system resources


will be serialized in and activated when needed in the future


e.g. Teller session bean who is logged into system and transfers funds
between accounts


Stateless session bean


does not maintain conversational state


each method is independent of another and the only information
needed is is supplied in the call parameters


e.g. Statement that is given a list of accounts or an owner to generate
a textual report for


consumes the least amount of resources among all the bean types

Enterprise JavaBeans

14

EJB Classes and Interfaces

Enterprise JavaBeans

15

EJB Conceptual Class Overview

Bean
ej bCreate( )
ej bPostCreate( )
ej bPassi vate( )
ej bActi vate( )
ej bLoad( )
ej bStore( )
ej bRemove( )
setEnti tyContext( )
unsetEnti tyContext( )
_Busi ness Methods_( )
<<Cl ass>>
*
bean pool
Contai nerRemoteInterfaceImpl
_Busi ness Methods_( )
<<Cl ass>>
Contai nerHomeInterfaceImpl
_Li fecycl e Methods_(
<<Cl ass>>
DatabaseAdapter
1
Remote Interface
_Busi ness Methods_( )
<<Interface>>
*
Contai ner
*
1
*
*
{ 10s of i nstances
per bean type }
{ mi l l i ons of i nstances }
{ one per bean type }
Cl i ent
Home Interface
_Li fecycl e Methods_(
<<Interface>>
*
JNDI
Enterprise JavaBeans

16

Bean Class Instance Lifecycle

No State

Pooled State

Ready State

1: newInstance()

2: setEJBContext()

3: bean associated


to an EJB Object

4: service client requests

5: bean disassociated


from EJB Object

Enterprise JavaBeans

17

Remote Interface


Defines the “business” methods that will be available to
clients in a distributed call


Account.debit(transactionRec) (EntityBean)


Teller.transfer(sourceAccount, targetAccount) (SessionBean)


Gets compiled by the ejb compiler to create RMI stubs and
skeletons


stubs are used by RMI to translate a method invocation to wire
format


skeletons are used by RMI to translate wire format to a method
invocation

Enterprise JavaBeans

18

Remote Interface (cont.)


Defined as a Java interface


extends javax.ejb.EJBObject


extends java.rmi.Remote


getEJBHome()
-

returns the Home object for the bean


getPrimaryKey()
-

returns the primary key for the object


getHandle()
-

returns a handle to object that may be used to re
-
establish communications at a later time; possibly in another server


remove()
-

removes this EJBObject object (prior to eviction)


isIdentical(EJBObject)
-

returns if both objects are same



Enterprise JavaBeans

19

Remote Interface Example:

Cabin

package com.titan.cabin;


import java.rmi.RemoteException;


public interface Cabin extends javax.ejb.EJBObject {


public String getName() throws RemoteException;


public void setName(String str) throws RemoteException;


public int getDeckLevel() throws RemoteException;


public void setDeckLevel(int level)


throws RemoteException;


public int getShip() throws RemoteException;


public void setShip(int sp) throws RemoteException;


public int getBedCount() throws RemoteException;


public void setBedCount(int bc) throws RemoteException;

}

Enterprise JavaBeans

20

Home Interface


Defines the “lifecycle” methods that will be available to
clients in a distributed call


create new bean objects, locate or remove existing bean objects


e.g. AccountHome.create(owner, initialBalance)


e.g. AccountHome.findByPrimaryKey(accountId)


e.g. TellerHome.create(login, pin)


e.g. MonthlyStatementHome.create()


Gets compiled by the ejb compiler to creates RMI stubs
and skeletons

Enterprise JavaBeans

21

Home Interface (cont.)


Defined as a Java interface


extends javax.ejb.EJBHome


extends java.rmi.Remote


getEJBMetaData()
-

returns metadata about the bean


remove(primaryKey)
-

removes object identified by primary key


remove(handle)
-

removes object identified by its EJBHandle


Enterprise JavaBeans

22

Home Interface Example:

CabinHome

package com.titan.cabin;


import java.rmi.RemoteException;

import javax.ejb.CreateException;

import javax.ejb.FinderException;


public interface CabinHome extends javax.ejb.EJBHome {



public Cabin create(int id)


throws CreateException, RemoteException;



public Cabin findByPrimaryKey(CabinPK pk)


throws FinderException, RemoteException;

}



Enterprise JavaBeans

23

Bean Class


Implements the business methods defined in the Object
interface


does not inherit

from the Object or Home interfaces


must have methods that match signatures supplied in all of the
Object interface and portions of the Home interface


Account.deposit(transactionRec)
-

AccountBean.deposit(transactionRec)


AccountHome.create(owner)
-

AccountBean.ejbCreate(owner)


the connection between the Object/Home interface calls and the
Bean implementation is done by the EJB compiler that creates the
container
-
specific skeletal code


uses the Deployment Descriptor to help generate glue code


similar in functionality to a C++ template or a C++ CORBA TIE class

Enterprise JavaBeans

24

Bean Class (cont.)


Clients never interact with bean classes themselves


always interact with the bean through home (create, find, remove)
and remote interfaces (business methods)


beans that interact with other beans are simply clients of the other
bean


stubs and skeletons are created from the interfaces that glue the
client, the database, and the bean code together




Enterprise JavaBeans

25

Bean Class (cont.)


implements javax.ejb.[Entity|Session]Bean


extends empty javax.ejb.EnterpriseBean; extends
java.io.Serializable


set/unset[Entity/Session]Context()



provides callback into container to find caller id, transaction
information, etc.


ejbCreate()


container calls this when the bean gets associated with an object


ejbPostCreate
() [ Entity Beans Only ]


container calls this after persisting the object’s state

Enterprise JavaBeans

26

Bean Class (cont.)


ejbPassivate()


container calls this method when the instance is being dis
-
associated with a particular EJB Object (pre serialization)


ejbActivate()


container calls this method when the instance is taken fro a pool of
available instances and associated with a particular EJB Object
(post de
-
serialization)


ejbRemove()


container calls this method of an instance before removing an EJB
Object from the system

Enterprise JavaBeans

27

Bean Class (cont.)


ejbLoad
() [ Entity Beans Only ]


container calls this method to instruct the instance to synchronize
its state with the state stored in the database


command (bean managed), completion event (container managed)


ejbStore
() [ Entity Beans Only ]


container calls this method to instruct the instance to synchronize
the state store in the database with its state


command (bean managed), completion event (container managed)


Enterprise JavaBeans

28

Bean Class Example:

CabinBean

package com.titan.cabin;


import javax.ejb.EntityContext;


public class CabinBean implements javax.ejb.EntityBean {



public int id;


public String name;


public int deckLevel;


public int ship;


public int bedCount;

Enterprise JavaBeans

29


Bean Class Example:

CabinBean (cont.)


public void ejbCreate(int id){


this.id = id;


}


public void ejbPostCreate(int id){


// Do nothing. Required in entity beans.


}


public String getName(){


return name;


}


public void setName(String str){


name = str;


}


public int getShip(){


return ship;


}

Enterprise JavaBeans

30

Bean Class Example:

CabinBean (cont.)


public void setShip(int sp) {


ship = sp;


}


public int getBedCount(){


return bedCount;


}


public void setBedCount(int bc){


bedCount = bc;


}


public int getDeckLevel(){


return deckLevel;


}

Enterprise JavaBeans

31

Bean Class Example:

CabinBean (cont.)


public void setDeckLevel(int level ){


deckLevel = level;


}


public void setEntityContext(EntityContext ctx){


// Not implemented.


}


public void unsetEntityContext(){


// Not implemented.


}


public void ejbActivate(){


// Not implemented.


}


public void ejbPassivate(){


// Not implemented.


}

Enterprise JavaBeans

32

Bean Class Example:

CabinBean (cont.)


public void ejbLoad(){


// Not implemented. Entity Beans


}


public void ejbStore(){


// Not implemented. Entity Beans


}


public void ejbRemove(){


// Not implemented.


}

}



Enterprise JavaBeans

33

Primary Key Class


Value that uniquely identifies the object in the database


Implements java.io.Serializable


Implements


hashCode()


equals()


toString() helpful


Contains identical public attributes from the Bean Class for those
that represent the bean’s primary key value(s).

Enterprise JavaBeans

34

Primary Key Class Example:

CabinPK

package com.titan.cabin;

public class CabinPK implements java.io.Serializable {


public int id;


public int hashCode( ){


return id;


}


public boolean equals(Object obj){


if(obj instanceof CabinPK){


return (id == ((CabinPK)obj).id);


}


return false;


}


public String toString(){


return String.valueOf(id);


}

}



Enterprise JavaBeans

35

Containers


Manages interaction between the bean and its server


Provides a uniform interface to the bean and to the server

Enterprise JavaBeans

36

Containers (cont.)


Creates new instances of beans and manages their
persistence


provides mapping between bean and container’s underlying
database


provides the skeletal class code for the home and remote interfaces


e.g. AccountHome.create()


container supplies code to create row in database, instantiate an EJB
Object to represent that instance of an account


e.g. AccountHome.remove(accountPK)


container supplies code to remove row in database and remove any
existing EJB Objects


e.g. Account.debit(transactionRec)


container supplies code to obtain the entity from storage, locate a bean to
take on its state, and invoke behavior on the bean


Enterprise JavaBeans

37

Deployment Descriptor


Instructs the server on the type of bean (session or entity)


Instructs the server how to apply services to the bean


Described in XML; ejb
-
jar.xml


Created from IDE or text source


Supplied with other bean components in a “jar” (Java
archive) file


bean class


remote interface


home interface


primary key (for entity beans)


deployment descriptor


rmi stub/skeleton

Enterprise JavaBeans

38

Deployment Descriptor Example:

ejb
-
jar.xml (Cabin)

<?xml version="1.0" ?>

<!DOCTYPE ejb
-
jar PUBLIC "
-
//Sun Microsystems, Inc.//DTD Enterprise JavaBeans
1.1//EN" "http://java.sun.com/j2ee/dtds/ejb
-
jar_1_1.dtd">

<ejb
-
jar>


<enterprise
-
beans>


<entity>


<description>This Cabin enterprise bean entity represents a cabin on a cruise
ship.</description>


<ejb
-
name>CabinBean</ejb
-
name>


<home>com.titan.cabin.CabinHome</home>


<remote>com.titan.cabin.Cabin</remote>


<ejb
-
class>com.titan.cabin.CabinBean</ejb
-
class>

Enterprise JavaBeans

39

Deployment Descriptor Example:


(cont.)


<persistence
-
type>Container</persistence
-
type>


<prim
-
key
-
class>com.titan.cabin.CabinPK</prim
-
key
-
class>


<reentrant>False</reentrant>


<cmp
-
field> <field
-
name>id</field
-
name> </cmp
-
field>


<cmp
-
field> <field
-
name>name</field
-
name> </cmp
-
field>


<cmp
-
field> <field
-
name>deckLevel</field
-
name> </cmp
-
field>


<cmp
-
field> <field
-
name>ship</field
-
name> </cmp
-
field>


<cmp
-
field> <field
-
name>bedCount</field
-
name> </cmp
-
field>


</entity>


</enterprise
-
beans>


...

</ejb
-
jar>


Enterprise JavaBeans

40

EJB Object class


Written by the container
-
specific compiler after processing
the deployment descriptor


Implements methods

defined

in remote interface

by delegating them to

an instance of the bean

class


EJBObject

getEJBHome( )

getPrimaryKey(

getHandke()

remove( )

isIdentical( )

<<Interface>>

Account

debit( )

credit( )

getBalance(

<<Interface>>

Account_EJBObject

AccountBean

id_

balance_

ejbCreate (balance)

ejbPostCreate (balance)

ejbPassivate ()

ejbActivate ()

ejbLoad ()

ejbStore ()

ejbRemove ()

setEntityContext ()

unsetEntityContext ()

EntityBean

ejbPassivate( )

ejbActivate( )

ejbLoad( )

ejbStore( )

ejbRemove( )

setEntityContext( )

unsetEntityContext( )

<<extends>>

<<implements>>

<<implements>>

Enterprise JavaBeans

41

EJB home class


Written by the container
-
specific compiler after processing
the deployment descriptor


Implements methods defined in home interface


locate


create


remove


Handles interactions with resources pools, persistence
mechanism, and resource managers

Enterprise JavaBeans

42

Example Client

Context jndiContext = getInitialContext();

Object obj = jndiContext.lookup("ejb/CabinHome");

System.out.println("found it! ="+ obj);

CabinHome home =
(CabinHome)javax.rmi.PortableRemoteObject.narrow(obj,
CabinHome.class);


System.out.println("narrowed it! ="+ home);


Cabin cabin_1 = home.create(1);

System.out.println("created it! ="+ cabin_1);

cabin_1.setName("Master Suite");

cabin_1.setDeckLevel(1);

cabin_1.setShip(1);

cabin_1.setBedCount(3);

Enterprise JavaBeans

43

Example Client


CabinPK pk = new CabinPK();

pk.id = 1;

System.out.println("keyed it! ="+ pk);



Cabin cabin_2 = home.findByPrimaryKey(pk);

System.out.println("found by key! ="+ cabin_2);

System.out.println(cabin_2.getName());

System.out.println(cabin_2.getDeckLevel());

System.out.println(cabin_2.getShip());

System.out.println(cabin_2.getBedCount());


Enterprise JavaBeans

44

Usage Scenarios

Enterprise JavaBeans

45

Creating an Account Object

AccountHome_EJBHome

Client

1: createAccount(10.00)

Account_EJBObject

2: new Account_EJBObject

AccountBean

4: ejbCreate(10.00)

6: ejbPostCreate(10.00)

7: ejbPassivate()

AccountBean

AccountBean

AccountBean

bean pool

3: select instance

8: return instance

database

5: insert

remote interface

Enterprise JavaBeans

46

Accessing an Account Object

Client

1: debit(10.00)

Account_EJBObject

AccountBean

4: populate state

5: ejbLoad()

6: debit(10.00)

7: ejbStore()

AccountBean

AccountBean

AccountBean

bean pool

3: select instance

10: return instance

database

2: select

8: update

Enterprise JavaBeans

47

Deleting an Account Object

AccountHome_EJBHome

Client

1: remove(pKey)

Account_EJBObject

AccountBean

4: populate state

5: ejbLoad()

6: ejbRemove()

AccountBean

AccountBean

AccountBean

bean pool

3: select instance

10: return instance

database

2: select

7: delete

8: remove()

Enterprise JavaBeans

48

Questions to Ponder...


Entity bean, stateful session bean, stateless session bean?


object which requires access by multiple clients over its lifetime


object whose work accepts and returns all information in the call


object that must exist after server crash


object that must exist between method invocations


object that encapsulates a set of client actions to multiple beans


Why is there not a ratio of 1:1 between instances of beans
(EJB Objects) and instances of the bean class?