Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enterprise Java Beans Overview

Similar presentations


Presentation on theme: "Enterprise Java Beans Overview"— Presentation transcript:

1 Enterprise Java Beans Overview
EJB Intro

2 Agenda Background EJB Overview Bean Types EJB Interfaces and Classes
EJB Intro

3 Applications 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 We have to write a lot of ‘plumbing’ code v EJB Intro

4 What didn’t we address ? Could someone else deploy your application?
Component reusability Security Threading Resource Management Load-Balancing Fault Tolerance (a little with activation) v EJB Intro

5 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 v EJB Intro

6 Components Vs. Objects Usually larger-grained
Provide a complete capability Credit Card Verification Can be customized for deployment v EJB Intro

7 Component Architectures
Client-Side Applets Java Beans ActiveX Server Side Servlets Enterprise Java Beans (EJB) CORBA Components Microsoft .NET v EJB Intro

8 Distributed Objects Makes business objects more accessible
permits more of an 3-tier architecture user interface at the first tier (Web Applications) business logic at the second tier (Business Applications) enterprise resources at the third tier (Databases) Key technologies include RMI, CORBA, and DCOM Provide for communication, but limited in server-side component support; results in “roll your own” component models v EJB Intro

9 Server-Side Components
Architecture for developing distributed business objects Separates the development from the assembly into specific applications allows for the sale of smaller/reusable components rather than end-to-end systems assembler determines actual transactional, security, persistence behavior, etc. for the component. v EJB Intro

10 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 v EJB Intro

11 Enterprise JavaBeans (EJBs)
Standard server-side component model for Java Enterprise Applications Enables large scale development Helps build portable applications 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 v EJB Intro

12 EJB Server-side Component Model
Encapsulates application’s business logic manage terms of an account manage state of an order provide tax calculations Normally accesses database or other backend systems EJB Clients implement only the presentation logic use EJBs for their business logic v EJB Intro

13 EJB Enables Large System Development
Distributed communication RMI, RMI-IIOP, CORBA-IDL Transaction management scope, isolation, lifecycle Resource pooling separation of bean state from object state Security class/method level, role based Threading container initiated Persistence container and bean managed v EJB Intro

14 EJB Resource Pooling Bean State connection Object Methods()
getCounty() getVotingDistrict() Bean Instance Bean Methods() ejbCreate() ejbActivate() ejbPassivate() ejbRemove() setEJBContext() unsetEJBContext() Object State name address Entity Beans Only Object State Object State Object State Bean Pool Bean Instance Bean Instance Database Bean Instance v EJB Intro

15 EJB Portability Java EJB components 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 Borland’s Enterprise AppServer ... v EJB Intro

16 EJB Architecture Interfaces and Classes Container Application Server
beans entity bean session session (no primary key) Stateless session bean Stateful session bean message driven bean (no primary key, home or object interface) primary key (entity beans only) home interface (local and remote) EJB object interface (local and remote) Container Application Server v EJB Intro

17 Bean Types Entity beans Session beans
models persistent state - this state is maintained through all method and server invocations nouns of the domain real world objects (e.g. Owner, Account, Transaction) Session beans models non-persistent state - this state will be lost between method invocations (stateless session) or server invocations (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 v EJB Intro

18 Bean Types (cont.) Message Driven beans
models non-persistent state - this state will be lost between message processing similar to Stateless Session Beans (which are invoked through synchronous RMI calls) invoked through asynchronous JMS Messages v EJB Intro

19 Bean Usage Entity beans Session 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 v EJB Intro

20 Bean Usage (cont.) Message Driven Bean
model business process invoked through asynchronous messages are not persisted to a database v EJB Intro

21 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 an transfers funds between accounts Stateless session bean do 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 v EJB Intro

22 Stateless Session Bean Lifecycle
v EJB Intro

23 Stateless Session Bean Conceptual Class Model
v EJB Intro

24 Stateful Session Bean Lifecycle
v EJB Intro

25 Stateful Session Bean Conceptual Class Model
v EJB Intro

26 Entity Bean Lifecycle v EJB Intro

27 Entity Bean Conceptual Class Model
v EJB Intro

28 Message Driven Bean Lifecycle
EJB Intro

29 Message Driven Bean Conceptual Class Model
EJB Intro

30 EJB Classes and Interfaces
Cabin Example from “Enterprise Java Beans, 3rd Edition”, Monson-Haefel v EJB Intro

31 Remote Interface Called “the EJB Object”
Defines the “business” methods that will be available to clients in a distributed call e.g. Account.debit(transactionRec) e.g. Teller.transfer(sourceAccount, targetAccount) Gets compiled by the ejb compiler to creates 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 v EJB Intro

32 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 v EJB Intro

33 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; } v EJB Intro

34 Local Interface (EJB 2.0) Like the Remote Interface, defines the “business” methods that will be available to clients, but only for local calls e.g. Account.debit(transactionRec) e.g. Teller.transfer(sourceAccount, targetAccount) Can only be used within the same JVM as the EJB Gets compiled by the ejb compiler to creates local stubs for container to interpose transactions, access control, etc. on invocations. v EJB Intro

35 Local Interface (EJB 2.0) (cont.)
Defined as a Java interface extends javax.ejb.LocalObject getEJBLocalHome() - returns the LocalHome object for the bean getPrimaryKey() - returns the primary key for the object remove() - removes this EJBObject object (prior to eviction) isIdentical(EJBObject) - returns if both objects are same not applicable extends java.rmi.Remote - it is a local object getHandle() - unnecessary since client/EJB in same JVM methods do not throw RemoteException; only EJBException v EJB Intro

36 Local Interface Example (EJB 2.0): Cabin
package com.titan.cabin; import javax.ejb.EJBException; public interface LocalCabin extends javax.ejb.EJBLocalObject { public String getName() throws EJBException; public void setName(String str) throws EJBException; public int getDeckLevel() throws EJBException; public void setDeckLevel(int level) throws EJBException; public int getShip() throws EJBException; public void setShip(int sp) throws EJBException; public int getBedCount() throws EJBException; public void setBedCount(int bc) throws EJBException; } v EJB Intro

37 Remote 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 v EJB Intro

38 Remote 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 defines create methods (create(<XXXX>)) finder methods (findBy<XXXX>(<YYYY>)) home methods (<XXXX>) //EJB 2.0 v EJB Intro

39 Remote 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; public int getDeckCount(int deck) throws RemoteException;//EJB2.0 } v EJB Intro

40 Local Home Interface (EJB 2.0)
Like the Remote 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() Can only be used within the same JVM as the EJB Gets compiled by the ejb compiler to creates stubs for container interpose on invocations v EJB Intro

41 Local Home Interface (cont.)
Defined as a Java interface extends javax.ejb.EJBLocalHome remove(primaryKey) - removes object identified by primary key not applicable extends java.rmi.Remote getEJBMetaData() - inserted in Remote Home for visual tools only remove(handle) - no need for handles in local JVM defines create methods (create(<XXXX>)) finder methods (findBy<XXXX>(<YYYY>)) home methods (<XXXX>) v EJB Intro

42 Local Home Interface Example (EJB 2.0): CabinHome
package com.titan.cabin; import javax.ejb.EJBException; import javax.ejb.CreateException; import javax.ejb.FinderException; public interface LocalCabinHome extends javax.ejb.EJBLocalHome { public LocalCabin create(int id) throws CreateException, EJBException; public LocalCabin findByPrimaryKey(CabinPK pk) throws FinderException, EJBException; public int getDeckCount(int deck) throws EJBException; } v EJB Intro

43 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(transarctionRec) 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 CORBA TIE class v EJB Intro

44 Bean Class (cont.) Clients never interact with bean classes themselves
always interact with the bean through home (create, find, remove) and remote/local 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 v EJB Intro

45 Bean Class (cont.) implements javax.ejb.[Entity|Session|MessageDriven]Bean extends empty javax.ejb.EnterpriseBean; extends java.io.Serializable set/unset[Entity|Session|MessageDriven]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 v EJB Intro

46 Bean Class (cont.) ejbPassivate() [ Session and Entity Beans Only]
container calls this method when the instance of the bean class is either being returned to the pool (Entity) or serialized/unloaded (Stateful) ejbActivate() [ Session and Entity Beans Only] container calls this method when the instance of the bean class is taken from a pool of available instances and associated with a particular EJB Object (Entity) or loaded/de-serialized (Stateful) ejbRemove() container calls this method of an instance before removing an EJB Object from the system v EJB Intro

47 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), preparation event (container managed) v EJB Intro

48 Bean Class (cont.) onMessage(Message msg) [ Message Driven Beans Only ] container calls bean method to handle message from Destination (Topic or Queue) v EJB Intro

49 Bean Class Example (EJB 2.0): CabinBean
package com.titan.cabin; import javax.ejb.EntityContext; public abstract class CabinBean implements javax.ejb.EntityBean { public abstract void setId(Integer id); public abstract Integer getId(); public abstract void setName(String name); public abstract String getName(); public abstract void setDeckLevel(int level); public abstract int getDeckLevel(); public abstract void setShipId(int ship); public abstract int getShipId(); public abstract void setBedCount(int count); public abstract int getBedCount(); v EJB Intro

50 Bean Class Example (EJB 2.0): CabinBean (cont.)
public Integer ejbCreate(int id){ this.setId(new Integer(id)); return null; } public void ejbPostCreate(int id){ // Do nothing. Required. //EJB 2.0 Home Method public int ejbGetDeckCount(int deck) { int count=0; //implementation not shown return count; v EJB Intro

51 Bean Class Example (EJB 2.0): CabinBean (cont.)
public void setEntityContext( // Not implemented. } public void unsetEntityContext(){ // Not implemented. public void ejbActivate(){ // Not implemented. public void ejbPassivate(){ // Not implemented. public void ejbLoad(){ // Not implemented. public void ejbStore(){ // Not implemented. public void ejbRemove(){ // Not implemented. v EJB Intro

52 Bean Class Example (EJB 1.1): CabinBean
package com.titan.cabin; import javax.ejb.EntityContext; public class CabinBean implements javax.ejb.EntityBean { public Integer id; public String name; public int deckLevel; public int shipId; public int bedCount; v EJB Intro

53 Bean Class Example (EJB 1.1): CabinBean (cont.)
public String getName(){ return name; } public void setName(String str){ name = str; } public int getShipId(){ return shipId; } public void setShipId(int sp) { shipId = sp; } public int getBedCount(){ return bedCount; } public void setBedCount(int bc){ bedCount = bc; } public int getDeckLevel(){ return deckLevel; } public void setDeckLevel(int level){ deckLevel = level } v EJB Intro

54 Bean Class Example (EJB 1.1): CabinBean (cont.)
public Integer ejbCreate(int id){ this.id = new Integer(id); return null; } public void ejbPostCreate(int id){ // Do nothing. Required. v EJB Intro

55 Bean Class Example (EJB 1.1): CabinBean (cont.)
public void setEntityContext( // Not implemented. } public void unsetEntityContext(){ // Not implemented. public void ejbActivate(){ // Not implemented. public void ejbPassivate(){ // Not implemented. public void ejbLoad(){ // Not implemented. public void ejbStore(){ // Not implemented. public void ejbRemove(){ // Not implemented. v EJB Intro

56 Primary Key Class Value that uniquely identifies the object in the database Implements java.io.Serializable Implemenets hashCode() equals() toString() helpful Contains identical public attributes from the Bean Class for those that represent the bean’s primary key value(s). v EJB Intro

57 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); v EJB Intro

58 Containers Manages interaction between the bean and its server
Provides a uniform interface to the bean and to the server v EJB Intro

59 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.findByPrimaryKey(accountPK) 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 obtain the EJB Object from storage, locate a bean to take on its state, and invoke behavior on the bean v EJB Intro

60 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 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 v EJB Intro

61 Deployment Descriptor Example: ejb-jar.xml (Cabin)
<?xml version="1.0" ?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" " <ejb-jar> <enterprise-beans> <entity> <description> This Cabin enterprise bean entity represents a cabin on a cruise ship. </description> v EJB Intro

62 Deployment Descriptor Example: ejb-jar.xml (Cabin)
<ejb-name>CabinBean</ejb-name> <home>com.titan.cabin.CabinHome</home> <remote>com.titan.cabin.Cabin</remote> <local-home>com.titan.cabin.LocalCabinHome</local-home> <local>com.titan.cabin.LocalCabin</local> <ejb-class>com.titan.cabin.CabinBean</ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> v EJB Intro

63 Deployment Descriptor Example: (cont.)
<cmp-version>2.x</cmp-version> <abstract-schema-name>Cabin</abstract-schema-name> <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>shipId</field-name> </cmp-field> - <cmp-field> <field-name>bedCount</field-name> </cmp-field> <primary-field>id</primary-field> </entity> </enterprise-beans> ... </ejb-jar> v EJB Intro

64 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( 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>> v EJB Intro

65 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 v EJB Intro

66 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); v EJB Intro

67 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()); v EJB Intro

68 Usage Scenarios v EJB Intro

69 Creating an Account Object
AccountBean database AccountBean 3: select instance 8: return instance AccountBean 5: insert bean pool 4: ejbCreate(10.00) 6: ejbPostCreate(10.00) 7: ejbPassivate() 1: createAccount(10.00) AccountHome_EJBHome remote interface 2: new Account_EJBObject Client Account_EJBObject AccountBean v EJB Intro

70 Accessing an Account Object
AccountBean database AccountBean 3: select instance 10: return instance AccountBean 2: select 8: update bean pool 4: populate state 5: ejbLoad() 6: debit(10.00) 7: ejbStore() Client Account_EJBObject AccountBean 1: debit(10.00) v EJB Intro

71 Deleting an Account Object
AccountBean database AccountBean 3: select instance 10: return instance 2: select 7: delete AccountBean bean pool 4: populate state 5: ejbLoad() 6: ejbRemove() 1: remove(pKey) AccountHome_EJBHome 8: remove() Client Account_EJBObject AccountBean v EJB Intro

72 Questions to Ponder... Entity bean, stateful session bean, stateless session, message driven bean? object which requires access by multiple clients over its lifetime object whose work accepts and returns all information in the call object whose work arrives through an asynchronous message object that sends asynchronous messages 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 instanced of beans (EJB Objects) and instances of the bean class? What GoF Pattern does this depict? Name that bean entity - session beans have only a single client stateless session entity - only type persisted statful session or entity bean, except that the entity bean doesn’t maintain a per-client context outside of a transaction session bean - either Scalability Flyweight and Proxy/Decorator - the bean class is the flyweight and the remote interface is a proxy/decorator that knows to have the state activated inside the flyweight v EJB Intro


Download ppt "Enterprise Java Beans Overview"

Similar presentations


Ads by Google