Enterprise Java Beans (EJB
Enterprise Java Beans (EJB
)
)
By
By
Janaranjani K
Outline
Outline
Introduction of EJBs.Introduction of EJBs.
EJB as a Business Tier Component.EJB as a Business Tier Component.
EJB fundamentals.EJB fundamentals.
Enterprise Beans.Enterprise Beans.
Foundation of EJB.Foundation of EJB.
What constitutes Enterprise Bean?What constitutes Enterprise Bean?
Session beans.Session beans.
Components of a Session beans.Components of a Session beans.
The Session EJB Lifecycle (includes stateful and stateless).The Session EJB Lifecycle (includes stateful and stateless).
An example of stateless session bean (which includes bothAn example of stateless session bean (which includes both
remote and local interface). remote and local interface).
Introduction to EJBs
Introduction to EJBs
Introduction to EJBs
Introduction to EJBs
EJB is a standard for building server side component in java. ItEJB is a standard for building server side component in java. It
defines a contract between the component and application server defines a contract between the component and application server that enables the component to run in any application server.
that enables the component to run in any application server.
EJB components (called as enterprise beansEJB components (called as enterprise beans) are) are
deployabledeployable importedimported loadedloaded
into an application server, which host all these components. into an application server, which host all these components.
Continued…
Continued…
Common Service includes:
Common Service includes:
Transaction ManagementTransaction Management
Resource ManagementResource Management
Connection poolingConnection pooling
SecuritySecurity
NetworkingNetworking
Persistant ManagementPersistant Management
ConcurrencyConcurrency
Location transparencyLocation transparency
EJB as a Business Tier
EJB as a Business Tier
Component
Component
Enterprise beans are intended for server side componentEnterprise beans are intended for server side component
development not for client side (which lies in presentation tier development not for client side (which lies in presentation tier and components like thick clients, web service clients
and components like thick clients, web service clients etc areetc are used for its development). So it lies in
used for its development). So it lies in Business Tier.Business Tier.
EJB component can perform the following tasks:EJB component can perform the following tasks:
Perform business logic.Perform business logic.
Access to the database.Access to the database.
E.g., Submitting an order for books.E.g., Submitting an order for books.
Enterprise bean can achieve database access usingEnterprise bean can achieve database access using JDBC.JDBC.
Access another system.Access another system.
EJB Fundamentals
EJB Fundamentals
Enterprise Beans
Enterprise Beans
An enterprise beanAn enterprise bean is a server side software component thatis a server side software component that
can be deployed in a distributed environment. can be deployed in a distributed environment.
It compose of one or more java objects.It compose of one or more java objects.
The client to an enterprise bean can be one of the following:The client to an enterprise bean can be one of the following:
A servlet A servlet
An applet An applet
Continued…
Continued…
Types of Beans:
Types of Beans:
Session beans.Session beans.
Stateful session beans.Stateful session beans.
Stateless session beans.Stateless session beans.
Entity beans.Entity beans.
Enterprise java Enterprise java beans beans BMP BMP CMP CMP Stateless Stateless Stateful Stateful Entity beans Entity beans MDBs MDBs Session Beans Session Beans
Diagrammatic
Diagrammatic
Representation
Representation
Session Beans
Session Beans
Session beans model business process.
Session beans model business process.
They are perform actions. Like,
They are perform actions. Like,
Adding numbers
Adding numbers
Accessing database
Accessing database
Unlike entity beans, they are
Unlike entity beans, they are non-persistant.
non-persistant.
Types:
Types:
Stateful session beans.Stateful session beans.
Stateful Session Beans
Stateful Session Beans
A stateful session bean maintains a
A stateful session bean maintains a conversational state
conversational state
The state is relevant only for a single client
The state is
relevant only for a single client
Cannot be seen by other clients
Cannot be seen by other clients
The state is not persistent
The state is
not persistent
Expires after a certain timeout
Expires after a certain timeout
It has performance hit due to
It has performance hit due to resource pooling.
resource pooling.
Stateless Session Beans
Stateless Session Beans
Conceptually, the same as stateful session beans.Conceptually, the same as stateful session beans.
No need to save the conversational state, so called Stateless.No need to save the conversational state, so called Stateless.
CanCan have fields, but they are not unique to have fields, but they are not unique to any clientany client
Since the container knows the bean has no state, it can:Since the container knows the bean has no state, it can:
Use a single bean instance (While each client thinks it has itsUse a single bean instance (While each client thinks it has its
own copy) own copy)
Destroy/re-instantiate on the flyDestroy/re-instantiate on the fly
Redirect requests to different instances (load balancing)Redirect requests to different instances (load balancing)
Client does not care on which server the bean is storedClient does not care on which server the bean is stored
Entity Beans
Entity Beans
Entity beans model Business Data.Entity beans model Business Data.
Object-oriented view of entities stored in Object-oriented view of entities stored in persistent storagepersistent storage
Normally, each instance represents a row in a relational DBNormally, each instance represents a row in a relational DB
table table
Persistence code can be written manually (bean-managedPersistence code can be written manually (bean-managed
persistence,
persistence, BMP BMP ) or automatically (container-managed) or automatically (container-managed persistence,
persistence, CMP CMP ))
A single bean instance (on the server) can be accessed byA single bean instance (on the server) can be accessed by
multiple clients multiple clients
Message Driven Beans
Message Driven Beans
New in EJB 2.0 standard
New in EJB 2.0 standard
Built on top of JMS to send m
Built on top of JMS to send messages to clients, which in
essages to clients, which in
turn would be received by
turn would be received by MDB.
MDB.
It is invoked by the container upon arrival of message at
It is invoked by the container upon arrival of message at
the destination that is serviced by
the destination that is serviced by the message-driven
the message-driven
bean.
bean.
Foundation of EJB
Foundation of EJB
EJB components are based on Distributed ObjectsEJB components are based on Distributed Objects
A distributed object is an object that is callable from a remoteA distributed object is an object that is callable from a remote
system. system.
The client can be in-process, out-of-process or a client locatedThe client can be in-process, out-of-process or a client located
elsewhere on the network. elsewhere on the network.
It does the invocation with the help of the followings:It does the invocation with the help of the followings:
Stubs (client side proxy object):Stubs (client side proxy object):
It masks the network communication from tIt masks the network communication from the client.he client.
It knows how to call over the network using the sockets, It knows how to call over the network using the sockets, massagingmassaging
parameters as necessary into their network representation. parameters as necessary into their network representation.
Skeleton (server side proxy object):Skeleton (server side proxy object):
It masks the network communication from tIt masks the network communication from the distributed object.he distributed object.
It understands how to receive calls on a network.It understands how to receive calls on a network.
Also knows how to massage parameters from the networkAlso knows how to massage parameters from the network
representation to their java r
representation to their java representations.epresentations.
It then delegates the call to the appropriate implementation object.It then delegates the call to the appropriate implementation object.
Distributed Architecture
Distributed Architecture
What constitutes Enterprise
What constitutes Enterprise
Bean?
Bean?
Enterprise Bean class:Enterprise Bean class:
It contains the implementation of your business logic.It contains the implementation of your business logic.
It can be session or entity or MDB.It can be session or entity or MDB.
Component Interface:Component Interface:
Remote Interface:Remote Interface:
It is the java interface that enumerates the businessIt is the java interface that enumerates the business
methods of your bean class. methods of your bean class.
Client code always go through the remote or local interfaceClient code always go through the remote or local interface
and never interacts with the bean directly. and never interacts with the bean directly.
It obeys the rules for It obeys the rules for java RMI-IIOP.java RMI-IIOP.
Continued…
Continued…
Continued…
Continued…
Local Interface:Local Interface:
It’s a high performing version of remote version.It’s a high performing version of remote version.
Used when you are calling the bean that presents in theUsed when you are calling the bean that presents in the
same process. same process.
Unlike remote interface, it will not undergo stubs, skeleton,Unlike remote interface, it will not undergo stubs, skeleton,
marshaling/demarshaling of parameters. marshaling/demarshaling of parameters.
EJB object:EJB object:
It is container generated implementations of the remoteIt is container generated implementations of the remote
interface. interface.
All client invoications go through this.It delegates the All client invoications go through this.It delegates the call tocall to
bean and implements the remote interface bean and implements the remote interface
Local home object:Local home object:
High performing version of home object.High performing version of home object.
Continued…
Continued…
Home interface:Home interface:
Java interface, acts as a EJB factory.Java interface, acts as a EJB factory.
Provides a handle of bean class to clientProvides a handle of bean class to client
Local Home interface:Local Home interface:
High version of Home interface.High version of Home interface.
Home object:Home object:
Container generated implementation of home interface.Container generated implementation of home interface.
Obeys RMI-IIOP rules.Obeys RMI-IIOP rules.
Local home object:Local home object:
High performing version of home object.High performing version of home object.
Continued…
Continued…
Deployment Descriptor:Deployment Descriptor:
An XML file, specifies the middleware requirements of your An XML file, specifies the middleware requirements of your
bean to the container. bean to the container.
Vendor specific files:Vendor specific files:
Enables you to take the advantage of vendor specific featuresEnables you to take the advantage of vendor specific features
EJB-jar file:EJB-jar file:
A complete zip of the above said A complete zip of the above said files.files.
Given to the application server.Given to the application server.
Application server unpacks the jar file and Application server unpacks the jar file and loads the bean into theloads the bean into the
container. container.
Session Beans
Session Beans
Components of a Session
Components of a Session
Beans
Beans
To define session bean X, you must create three classes:To define session bean X, you must create three classes:
The remote (local) component interface, calledThe remote (local) component interface, called X X (or (or X X Local)Local)
ExtendsExtends EJBObjectEJBObject (or (or EJBLocalObjectEJBLocalObject))
(All extended types are from(All extended types are from javax.ejbjavax.ejb))
The home interface, calledThe home interface, called X X Home (or Home (or X X LocalHome)LocalHome)
ExtendsExtends EJBHomeEJBHome (or (or EJBLocalHomeEJBLocalHome))
The bean class itself, calledThe bean class itself, called X X BeanBean
ExtendsExtends SessionBeanSessionBean
Should implementShould implement java.io.Serializablejava.io.Serializable (for stateful beans)(for stateful beans)
Implements business methods from the component interfaceImplements business methods from the component interface
ImplementsImplements lifecyclelifecycle methods (methods (ejbejbXXXXXX))
Stateful Session Bean’s
Stateful Session Bean’s
Lifecycle
Lifecycle Methods
Lifecycle Methods
Lifecycle methods are defined in theLifecycle methods are defined in the X X Bean classBean class
They are named ejb XXX They are named ejb XXX
ejbCreateejbCreate,, ejbActivateejbActivate, etc. plus, etc. plus setSessionContextsetSessionContext
No other method name should begin with ‘No other method name should begin with ‘ejbejb’’
Some lifecycle methods also appear in theSome lifecycle methods also appear in the X X Home interfaceHome interface
For session beans, only theFor session beans, only the createcreate methods appear in themethods appear in the
home interface home interface
In the home interface, the ‘In the home interface, the ‘ejbejb’ prefix is not used’ prefix is not used
i.e., method should be named ‘i.e., method should be named ‘createcreate’’
Lifecycle methods areLifecycle methods are invoked by the container invoked by the container when changingwhen changing
state during the bean’s life state during the bean’s life
ejbCreate Methods in
ejbCreate Methods in
Stateful Session Beans
Stateful Session Beans
A stateful session bean can contain severalA stateful session bean can contain several ejbCreateejbCreate
methods methods
The methods can have zero or more parametersThe methods can have zero or more parameters
They can be called asThey can be called as ejbCreateejbCreate(...) or (...) or ejbCreateejbCreate XXX (...), XXX (...),
for more descriptive names for more descriptive names
e.g.,e.g., ejbCreateByName(String name)ejbCreateByName(String name)
Must beMust be public voidpublic void
Should throwShould throw javax.ejb.CreateExceptionjavax.ejb.CreateExceptionif creation failsif creation fails
for whatever reason (invalid arguments, etc.) for whatever reason (invalid arguments, etc.)
Continued…
Continued…
Must be reflected in theMust be reflected in the X X Home interface (local or remote) by aHome interface (local or remote) by a
method with identical parameters, that is called ‘
method with identical parameters, that is called ‘createcreate’ or ’ or ‘‘createcreateXXX’XXX’
Returns the bean component interface type (Returns the bean component interface type ( X X ))
For remote homes, throwsFor remote homes, throws java.rmi.RemoteExceptionjava.rmi.RemoteException
e.g.,e.g., publicpublic XX createByName(String name) throwscreateByName(String name) throws
... ...
Activation and Passivation
Activation and Passivation
During the bean’s lifecycle, the container may decide toDuring the bean’s lifecycle, the container may decide to
passivate
passivate itit
Normally done to free up memory and other resourcesNormally done to free up memory and other resources
Bean is notified immediately before passivation by lifecycleBean is notified immediately before passivation by lifecycle
method
method ejbPassivateejbPassivate()()
In this method, the bean should:In this method, the bean should:
Release any resources it might be Release any resources it might be holdingholding
Sockets, Open files, database connections, etc.Sockets, Open files, database connections, etc.
Nullify fields that should not be serialized (Nullify fields that should not be serialized (cache, etc.)cache, etc.)
If the bean is referenced by client while passivated, the container If the bean is referenced by client while passivated, the container
activates
activates it.it.
Bean is notified byBean is notified by ejbActivateejbActivate() immediately after de-() immediately after
de-serialization serialization
The Lifecycle of Stateless
The Lifecycle of Stateless
Session EJBs
Session EJBs
Session EJBs have no state, so activation and Session EJBs have no state, so activation and passivation arepassivation are meaningless
meaningless
The container simply destroys instances when low on memory,The container simply destroys instances when low on memory,
and creates new ones as needed and creates new ones as needed
Still,Still, ejbActivateejbActivate andand ejbPassivateejbPassivate must be implementedmust be implemented
in
in X X Bean (as empty methods)Bean (as empty methods)
ejbCreate Methods in
ejbCreate Methods in
Stateless Session Beans
Stateless Session Beans
For stateless session beans, there can beFor stateless session beans, there can be only oneonly one ejbCreateejbCreate method, accepts zero parameters
method, accepts zero parameters
Reflected normally in the home interface as create.Reflected normally in the home interface as create.
Must beMust be public voidpublic void
Should throwShould throw javax.ejb.CreateExceptionjavax.ejb.CreateException if creation fails for if creation fails for whatever reason (invalid arguments, etc).
whatever reason (invalid arguments, etc).
Must be reflected in theMust be reflected in the X X Home interface (local or remote) by aHome interface (local or remote) by a method with identical parameters, that is called ‘
method with identical parameters, that is called ‘ createcreate’.’.
Returns the bean component interface type (Returns the bean component interface type ( X X ))
Sample Session Bean
Sample Session Bean
Deployment Descriptors
Deployment Descriptors
…. <enterprise-beans>…. <enterprise-beans> <session><session> <ejb-name>HelloWorldLocalBean</ejb-name><ejb-name>HelloWorldLocalBean</ejb-name> <home>examples.webservices.basic.localHome_Object.HelloWo<home>examples.webservices.basic.localHome_Object.HelloWo rldHome</home> rldHome</home> <remote>examples.webservices.basic.localHome_Object.HelloW<remote>examples.webservices.basic.localHome_Object.HelloW orldRemote</remote> orldRemote</remote> <ejb- <ejb-class>examples.webservices.basic.localHome_Object.HelloWorl class>examples.webservices.basic.localHome_Object.HelloWorl dLocalBean</ejb-class> dLocalBean</ejb-class> <session-type>Stateless(stateful)<session-type>Stateless(stateful)</session-type></session-type> <transaction-type>Container</transaction-type><transaction-type>Container</transaction-type> </session></session> </enterprise-beans> ….</enterprise-beans> ….
An example of stateless
An example of stateless
session bean.
Session Bean Class
Session Bean Class
package examples.webservices.basic.localHome_Object;package examples.webservices.basic.localHome_Object;
import javax.ejb.SessionBean;import javax.ejb.SessionBean;
import javax.ejb.CreateException;import javax.ejb.CreateException;
import javax.ejb.SessionContext;import javax.ejb.SessionContext;
public class HelloWorldLocalBean implements SessionBean{public class HelloWorldLocalBean implements SessionBean{
private SessionContext ctx;private SessionContext ctx;
public void ejbCreate() {}public void ejbCreate() {}
public void ejbActivate() {}public void ejbActivate() {}
public void ejbPassivate() {}public void ejbPassivate() {}
public void setSessionContext(SessionContext ctx) {public void setSessionContext(SessionContext ctx) {
this.ctx = ctx;this.ctx = ctx;
}}
public String sayHelloMethod(int num, String s) {public String sayHelloMethod(int num, String s) {
System.out.println("sayHello in webservices.basic.javaclassSystem.out.println("sayHello in webservices.basic.javaclass
webservice has "+ webservice has "+
"been invoked with arguments " + s + " and " + num+" the"been invoked with arguments " + s + " and " + num+" the
context is : "+ctx); context is : "+ctx);
String returnValue = "HelloWorldLocalBean....:This messageString returnValue = "HelloWorldLocalBean....:This message
brought to you by the "+ brought to you by the "+
"letter "+s+" and the number "+num+" the context is : "+ctx;"letter "+s+" and the number "+num+" the context is : "+ctx;
return returnValue;return returnValue;
}}
package examples.webservices.basic.localHome_Opackage examples.webservices.basic.localHome_Object;bject;
import javax.ejb.EJBHome;import javax.ejb.EJBHome;
import javax.ejb.CreateExceptiimport javax.ejb.CreateException;on;
import java.rmi.RemoteExceptiimport java.rmi.RemoteException;on;
public interface HelloWorldHome extends EJBHome{public interface HelloWorldHome extends EJBHome{
HelloWorldRemote create() throws CreateException,HelloWorldRemote create() throws CreateException, RemoteException ; RemoteException ; }}
Home Interface
Home Interface
Remote Interface
Remote Interface
package examples.webservices.basic.localHome_Object;package examples.webservices.basic.localHome_Object;
import java.rmi.RemoteException;import java.rmi.RemoteException;
import javax.ejb.EJBObject;import javax.ejb.EJBObject;
public interface HelloWorldRemote extends EJBObject {public interface HelloWorldRemote extends EJBObject {
public String sayHelloMethod(int num, String s) throwspublic String sayHelloMethod(int num, String s) throws
RemoteException; RemoteException; }}
Local Home Interface
Local Home Interface
package examples.webservices.basic.localHome_Object;package examples.webservices.basic.localHome_Object;
import javax.ejb.EJBLocalHome;import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;import javax.ejb.CreateException;
public interface HelloWorldLocalHome extends EJBLocalHome{public interface HelloWorldLocalHome extends EJBLocalHome{
HelloWorldLocal create() throws CreateException;HelloWorldLocal create() throws CreateException;
Local Interface
Local Interface
package examples.webservices.basic.localHome_Object;package examples.webservices.basic.localHome_Object;
import javax.ejb.EJBLocalObject;import javax.ejb.EJBLocalObject;
public interface HelloWorldLocal extends EJBLocalObject {public interface HelloWorldLocal extends EJBLocalObject {
public String sayHelloMethod(int num, String s);public String sayHelloMethod(int num, String s);
}}
Deployment Descriptor
Deployment Descriptor
<?xml version="1.0" encoding="UTF-8"?><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD
Enterprise JavaBeans 2.0//EN" Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb- jar_2_0.dtd"> jar_2_0.dtd"> <ejb-jar><ejb-jar> <enterprise-beans><enterprise-beans> <session><session> <ejb-name>HelloWorldLocalBean</ejb-name><ejb-name>HelloWorldLocalBean</ejb-name> <home>examples.webservices.basic.localHome_Object.HelloWo<home>examples.webservices.basic.localHome_Object.HelloWo rldHome</home> rldHome</home> <remote>examples.webservices.basic.localHome_Object.HelloW<remote>examples.webservices.basic.localHome_Object.HelloW orldRemote</remote> orldRemote</remote>