Java Ejb Tutorial
Java Ejb Tutorial
IN 30 MIN’s
DO YOU WANT
TO ANSWER MOST THEN LET ME
OF THE
HELP YOU!
EJB QUESTIONS ?
EJB
BY
Kantimahanti Prasad
[email protected] or [email protected]
Specializes in
Architecture, Designing, Development & Managing day-to-day activities.
His present & past working experiences in various global locations are in corporates like
Pramerica (Prudential U.S), J P Morgan Chase, A B N Amro Bank & SGS.
He was a part time visiting faculty in affiliates of Sydney University, Australia and All India Management
Institute teaching I.T, Project Management & Statistics. He has given some presentations on Project
Management and TQM at various venues. He has won few Talent/STAR performance awards and plays
almost all the sports what are under the Sun.
He hails from Vizag/ Hyderabad – India. His 3rd party tested Temperament Sorter results are below
https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800
https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606
If you liked his presentation, tell others and if you have a comment, tell him. He can be reached at
[email protected] or [email protected]
3. Thank you note
He wishes to thank Paul Perrone , Paulo Merson & Ramesh Behra for making
this tutorial look the way it does.
He wishes to thank to Katherine Ballantyne, Choi Kwan who volunteers to
edit all of his Articles & Presentations.
He wishes to thank Joerg Mueller, Muruganandam, CharlesJohnson & Venu
Gadium who had volunteered to do the editing of this presentation.
Dr.Rao &
ARUNA SUNAYANA SADHGI his Parents his Brothers his Sisters & his Cousins
Family
DEDICATED TO
Copyright 2004 Kanti Prasad All rights reserved
4. Component Technology
Properties Reusability
Operations Shareable
Events Distributable
Self description
Properties
Operations
Events
• Hardware
• The underlying operating system
• Their Application Server
• The network protocol they use
Remote
EJB Container
CLIENTS
EJB
Local
CLIENTS Remote
Possible CLIENTS
Remote
CLIENTS
Remote
CLIENTS
• Directory Services
• Distributed transaction management
• Security management
• Concurrent access management
• Persistence management
• Resource pooling (e.g. DB connections)
• Administration interface
• Load Balancing
• Fault tolerance
App Server
EJB Container
EJB
EJB
EJB
CLIENT
Pool
EJB EJB DB
Network
CLIENT EJB
App Server
EJB Container
EJB
EJB EJB
Container
Network intercepts
STUB
requests
CLIENT
Container knows what to do, as you describe everything in a special descriptor file
Copyright 2004 Kanti Prasad All rights reserved
17. J2EE Overview
Deployment
Descriptors (DDs)
Applet RMI/
Web Container EJB Container
IIOP
Container HTTP/S
JSP Servlet EJB
Applet
JSP Servlet ENGINE
JAX- J J W J Java Mgmt J J JAX- J J W J Java Mgmt J J
J C J C
J2SE RPC A A E M Mail N D RPC A A E M Mail N D
T O T O
X C B S JMX A D N B X C B S D B
SAAJ JAF SAAJ JAF JMX A N
R C S I C R C S I C
3 TIER 4 TIER
Client
RMI/
EIS
JAX- J W Mgmt J IIOP
J C DAO
RPC A E D
M O
X B JMX B DB
SAAJ S N
R S C
J2SE 2 TIER
MainFrames
EJB Client
EJB Impl
LocalHome Local create timeout
Client Process create invoke remove passivate
remove find activate
find invoke load
Home store
STUB STUB
create
remove
EJB find
Client Remote Network
EJB
Delegate
Delegate
Delegate Pool
invoke Delegate
Deployment Specialist
deploys apps and understands architecture issues
deploys system
supplies tools builds application
Application Assembler
Tools Provider Deployer System Administrator
maintains deployment
javax.ejb.EnterpriseBean interface
extends
we have written
Container implements/autogenerates code for the Interfaces
We will write only this Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING
JNDI Server returns ref of Home Stub 2 goes to the JNDI Server
7 and gets the EJB Object
C End
App Server
EJB Container
EJB Home or e.g
EJB Local Home Session Bean •Bank teller
instance •Credit Card authorization
EJB Object or
EJB Local Object Entity Bean e.g
Application RMI/ instance •Bank account balance
Client IIOP
•Purchase order
SESSION BEANS are like VERBS as they represent action or business process related logic.
If all the processing is done in the same Application server then we use
EJB Local(Object & Home) interfaces. Using local interfaces are optional.
Local interfaces pass by REFERENCE and EJB (Object/Home) pass by VALUE.
Copyright 2004 Kanti Prasad All rights reserved Using local interfaces avoids stubs, skeletons, network and so it is faster.
29. EJB Client
EJB clients
EJB implementation
ejbRemove()
setSessionContext()
ejbCreate()
Pool of equivalent
method ready instances
Client called another
Transactional business method
on the EJB Object. Transactional
Business Method
37. Stateful Session EJBs View
Stateful Session
EJB Client
LocalHome Local Logic
Client Process
State
Home
EJB input
Remote Network
Client EJB Pool output
The create method takes arguments The create method does not take arguments
e.g. create(String id) , create(int I , String id) e.g create()
There can be one or more arguments in a create method There can be no arguments in a create method
e.g e.g
An EJB that unzips 100 bytes of data An EJB that books a flight and rents a car at a travel agent’s
An EJB that checks to see if a stock symbol is valid web site.
App Server
EJB Container
CLIENT
EJB DB
Network
CLIENT EJB
Container decided it
Container decided it Does not exiist doesn’t need the
needs another
Entity Bean instance
Entity Bean insinstance
anymore
newInstance() unsetEntityContext()
Container decided it
Container decided it does not exiist doesn’t need the
needs another
Entity Bean instance
Entity Bean in
anymore
newInstance() unsetEntityContext()
The developer takes care of handling persistence Vendor takes care of everything by using O-R or OODB
mappings using metadata.
BMP uses hard coded queries so we can optimize our A developer cannot optimize performance as the vedor
queries takes care of it
We should start developing CMP beans, unless we require some kind of special bean, like multi-tables, that
cannot be completely realized with a single bean. Then when we realize that we need something more or that
we prefer handling the persistence (performance issue are the most common reason), we can change the bean
from a CMP to a BMP
Asynchronous messaging
Container decided it
needs another Does not exiist
Message DrivenBean
Instance
newInstance()
ejbRemove()
setMessageDrivenContext()
ejbCreate()
Pooled
onMessage()
51. Deployment
Declaring without programming helps the application assembler to change the XML file easily.
BEAN Provider declares components’ middleware service requirements in a DEPLOYMENT DESCRIPTOR File.
Bean Provider describes how the Container should perform the LifeCycle Management, Persistence, Transaction and Security.
2
Write the Deployment descriptor Start your EJB container and
6 confirm that it has loaded
the EJB Jar file.
Compile all the STEP 1 files into 3
.class files
Connect to your EJB by writing a test
7 Client .java file compile it and run it .
Using the Jar utility create an EJB Jar
file containing STEP 2 & STEP 3 files 4
End
C
Please download the trial Application Server software from the links provided on the Reference slide at the end.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import java.io.Serializable;
import java.rmi.RemoteException; Importing the required files
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface HelloHome extends javax.ejb.EJBHome
Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome
{
Hello create() throws java.rmi.RemoteException,
javax.ejb.CreateException; Interface methods should end with a semicolon ;
This method creates/manufactures the EJBObject and returns it . This create() method corresponds to the
ejbCreate() method in HelloBean.
As for every Interface we need implementation,Note
so Container will implement
In Home Interface we are(autogenerate code) forRemote
throwing 2 exceptions this Home
andInterface
Create . for us, which is the EJBHome Object
}
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome
Clients interact with the EJB Object through this Remote interface that is why we need to write this interface.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import java.util.*;
import javax.ejb.EJBObject; Importing the required files
import java.rmi.RemoteException;
public interface Hello extends javax.ejb.EJBObject
{ Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject
Clients interact with the EJB Object through this Local interface when there is no network involved..
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.ejb.EJBLocalObject;
public interface HelloLocal extends javax.ejb.EJBLocalObject
Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject
{
public String hello() ; Interface methods should end with a semicolon ;
As our requirement wants a business logic to greet Hello World a single method would be sufficient .
} As Local interface is used to interact with the Bean we need to mirror all the method signatures what
are there in a Bean class so that is why we are writing only one method in this Local interface.
Note As there is no remote calls no Remote Exception is thrown
As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Interface for us, which is the EJB Local Object
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import java.util.*;
Importing the required files
import javax.ejb.*;
public class HelloBean implements javax.ejb.SessionBean
NOTE : Note
If it is: Entity
this isBean
a class
weand
will not
implement
an Interface
javax.ejb.EntityBean
like the other two
and
(Home
if it is /Message
Remote).driven
This isbean
implementing
we will implement
SessionBean
javax.ejb.MessagedrivenBean
so it is a Session Bean
{ As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean .
As a Bean provider we need to specify the Middleware needs through this descriptor.
<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc. // DTD Enterprise JavaBeans 2.0 //
EN “ “ http://java.sun.com.dtd/ejb-jar_2_0.dtd”> XML Standard requirement
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name> Hello </ejb-name> The nickname for this particular Bean
<home>examples.HelloHome</home> The fully qualified name of the Home Interface
<remote>examples.Hello</remote> The fully qualified name of the Remote Interface
<local-home>examples.HelloLocalHome</local-home>
The fully qualified name of the Local HomeInterface
<local>examples.HelloLocal</local> The fully qualified name of the Local Interface
<ejb-class>examples.HelloBean</ejb-class> The fully qualified name of the EJB Class
<session-type>Stateless</session-type> Whether the session bean is stateful or stateless
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
Copyright 2004 Kanti Prasad All rights reserved
63. The Client
So now lets code our Client to access our simple stateless session bean.
package examples; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.naming.Context;
import javax.naming.InitialContext; importing the necessary files
import java.util.Properties;
public class HelloClient { As there is static key word this main method executes first before any other method in that class
NOTE : To call Local Interface you need not cast with the PortableRemoteObject. So the
block in red will be changed to
Object obj = ctx.lookup(“java:comp/env/HelloLocalHome”); ( to get a ref to LocalHome Object)
Copyright 2004 Kanti Prasad All rights reserved HelloLocalHome home = (HelloLocalHome)obj;
64. EJB Jar File
The folder structure within the Ejb-jar file is
META-INF/MANIFEST.MF
META-INF/ejb-jar.xml
examples/HelloBean.class
examples/HelloLocalHome.class
examples/HelloLocal.class
examples/Hello.class
Properties Remote/Local
File Interface
Deployment Jar
Descriptor Manifest
DEPLOYED
Jar file is a .ZIP compression format . META-MF file is a listing file automatically created by the Jar utility.
Please read the Deployment instructions provided by the Application server as it is Vendor specific
Deployment
.JAR .WAR
Jar Descriptor
file
Deployment
Tool
JAR ARC HIEVE (.jar)
WEB ARCHIEVE (.war)
EJB-JAR.XML
REMOTE WEB.XML
HOME Enterprise Archive HTML
EJB JSP
(.EAR Files) Servlets
(Application.XML)
import java.util.*;
import javax.ejb.EJBObject; Importing the required classes
import java.rmi.RemoteException;
import samples.ejb.stateful.simple.tools.BookException;
Remote Cart is extending EJBObject means Cart has all the behaviour of it
public interface Cart extends EJBObject Our bean class CartBean methods are mirrored here
{
import java.io.Serializable;
import java.rmi.RemoteException;
Importing the required classes
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
In a Stateful Bean you can have more than one create method taking arguments
Cart create(String person) throws RemoteException, CreateException;
import java.util.*;
import javax.ejb.*;
import samples.ejb.stateful.simple.tools.BookException; Importing the required classes
import samples.ejb.stateful.simple.tools.IdVerifier;
customerId = "0";
contents = new Vector(); as this is the Bean class we will implement the business logic here
}
NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean
public void ejbRemove() {} We need to write these methods as we are implementing SessionBean
Rules of implement states we need to implement all methods that are there in the implemented interface
shoppingCart.removeBook("Alice in Wonderland");
shoppingCart.remove(); Removing a particular book using the bean class method removeBook through
remote interface Cart –as we defined it this way
System.exit(0); Cart shoppingCart = home.create("Duke DeEarl","123");
/**
* Default constructor.
*/
public BookException() {
}
/**
* Constructor with a <code>String<code> as a parameter.
* @param msg message, describing the exception.
*/
public BookException(String msg) {
super(msg);
}
}
package samples.ejb.stateful.simple.tools;
/**
* Default constructor.
*/
public IdVerifier() {
}
ActiveX
Uses Microsoft’s architecture for determining how clients’
invocation requests are sent to components. DCOM used as
underlying transport mechanism
CORBA
ORB makes use of GIOP and other protocols to perform IPC
EJB
exports operations through Remote Interface
ActiveX
exports operations in the same interface
CORBA
exports methods through Interface Repository
ActiveX
Transactions, database management, legacy integration have to be coded
into the logic of the component. Security policy can be inherited from
NTLM. Transactions can be aided through MTS
CORBA
CORBAServices have different APIs. CORBAServices can be complicated
to code with. CORBAServices are not supported by all ORBs
Copyright 2004 Kanti Prasad All rights reserved
81. Component Comparison
Components provide interfaces in the form of Properties.
EJB
Properties are not explicitly exported but can be
mimicked through accessor operations
ActiveX
exports Properties in the same interface
CORBA
Properties not explicitly exported but can be
mimicked through attributes
EJB
Events supported through JMS with Message
Driven Bean
ActiveX
exports Events in the same interface
CORBA
Events supported through Event Service but cannot
be exported
EJB
Incorporating the contents of an EJB can be done
in two ways:
• by having the new EJB use the services of an old
EJB as a direct client
or
• by writing an EJB class that inherits from an
existing one
Active X
Incorporating the contents of an ActiveX can be done
in two ways:
CORBA
Every CORBA object has to have its own interface
definition
ActiveX
uses Microsoft's in–process/out-of-process architecture for sharing
multiple ActiveX components and Client components.
CORBA
ORB makes multiple instances of CORBA objects. Clients’ contexts are
managed by ORB but can behave differently based upon vendor’s
Implementation.
Copyright 2004 Kanti Prasad All rights reserved
87. Conclusion
We successfully completed a Tour on EJB . We looked at how an EJB is identified. How many
different types of EJBs’ are there and what each EJB type implements. Why
LocalInterfaces were introduced. We disected the EJB and went deeper into each part i.e. BEAN
Class, Remote Interface, EJB Object, Local Object, Local Interface, Home Object. We looked
Into the deployment descriptor and also seen all the files in EJB–Jar. We looked into each
Beans
Methods and also learned why we needed those methods. We had done 2 different Beans
examples and we were directed to the Web links where all the examples are demonstrated.
Once
you can get an idea of all the Interfaces, methods & exceptions raised, you can attempt to
try
some examples to get familiar and master EJB. There are nearly 100s’ of Application servers
but in this presentation you can see a few majorly used AppServers sample
implementation
web links. Just download any one of them and try out for yourself.
CONGRATULATIONS!
Now you know If you have any comments or appreciations then please email him at
as much as he [email protected], [email protected]
know of EJB He likes to hear your feed back!
Application Servers download information . Most of them are either free or have a 60 day trial version
For JBOSS Open Source go to http://www.jboss.org/downloads/index
http://www.kevinboone.com/jboss_tut_1.html
SUN’s downloads and examples
http://developers.sun.com/prodtech/javatools/jsstandard/reference/docs/s1s5/partsuppliers.html
http://java.sun.com/j2se/1.4.2/download.html ,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/
http://java.sun.com/developer/onlineTraining/EJBIntro/EJBIntro.html
BEA WebLogic downloads and examples Covers
http://commerce.bea.com/index.jsp , http://www.weblogic.com/docs/examples/index.html 90 % of the
MARKET
http://dev2dev.bea.com/codelibrary/code/examples_ejb20.jsp
WebSphere downloads and examples
http://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.html
REDHAT Application Server and Examples
http://www.redhat.com/docs/manuals/rhaps/jonas-guide/