Title: Enterprise JavaBeans (EJB)
1Enterprise JavaBeans (EJB)
2Enterprise JavaBeans (EJB)
- Enterprise JavaBeans provides a standard
distributed computing model. - EJB component is a JavaBean component, but
moreover EJB architecture provides a framework
which consists transaction processing, security,
persistence, and resource pooling facilities.
3What is EJB?
- EJB is a standard for building MIDDLEWARE in
multi-tiered solutions. - EJB is a solution to provide services that are
hard to implement for the users. - EJB architecture is a component architecture for
the deployment and development of component-based
distributed business applications.
4EJB API
- EJB API is a standard extension to java,
available in the javax.ejb package. - EJB is a specification for how distributed
components should work within the java
environment. - To use EJB objects, you need to install an
EJB-enabled server.
5EJB Container
- EJB-enabled application servers.
- EJB Container and Deployment Tools.
- Available from BEA, IBM, Sun Java System
Application Server and many other vendors. - Open source Glassfish, JBoss,
6EJB Container
EJB Container
EJB Client
Transaction management Persistence
Management Security Management Resource Pooling
EJB Context, JNDI
Bean
Business Methods
7Where is EJB in a Big Picture of J2EE?
Source Sang Shin, Enterprise JavaBeans TM (EJB
TM Architecture Overview) Technology and XML
8An EJB Environment
Source Java Enterprise in a Nutshell
9EJB Client
- An EJB client uses remote EJB objects to access
data and perform the tasks. - EJB clients are application clients that interact
with the J2EE EJB tier. - EJB clients are GUI programs that typically
execute on a desktop computer or they are web
applications they manage their own GUI and offer
a user experience similar to that of native
applications.
10Types of EJB
- There are three types of EJBs
- Entity bean
- corresponds to a record in a database
- Session bean
- handles business flow (stateless and stateful)
(one per client, only in stateless then may be
shared) - Message-Driven Beans (EJB version 2.0)
11Session Beans
- Does work on behalf of a single client.
- Is not persistent and hence relatively short
lived. - Is removed when the EJB server crashes
- Does not represent data in data store, although
can access/update such data.
Source Sang Shin, Enterprise JavaBeans
12When to Use Session Beans?
- to model process or control objects specific to a
particular client. - to model workflow, processes or tasks, manage
activities (make reservation, purchase...). - to coordinated processes between entity beans,
control interactions of beans. - to move business application logic from Client to
the Server Side.
Source Sang Shin, Enterprise JavaBeans
13Types of Session Beans
- Stateless execute a request and return a result
without saving any client specific state
information. It is shared among a number of
clients. - transient
- temporary piece of business logic needed by a
specific client for a limited time span - Stateful is created for a specific client and
maintains client specific state.
Source Sang Shin, Enterprise JavaBeans
14Where to use different types of Session Beans
- Stateless session beans
- Catalog
- No client specific state needs to be preserved
- Interest calculator
- No client specific state needs to be preserved
- Business logic with no need for database access
- Stateful session beans
- Shopping cart
- Client specific state needs to be preserved
Source Sang Shin, Enterprise JavaBeans
15Entity Beans
- Provides object view of data in data store
- Its lifetime is not related to the duration of
interaction with clients. - Lives as long as data exists in database (i.e.
long lived). - In most cases, synchronised with relational
databases. - Shared access among clients.
Source Sang Shin, Enterprise JavaBeans
16Entity Beans (contd)
- Clients normally look up (find) an existing
entity EJB - Creation means adding a row to a database table.
- Finding means finding a row in a existing
database table. - Entity bean instance has unique identifier called
primary key - Primary key can be any class
Source Sang Shin, Enterprise JavaBeans
17Examples of where to use Entity Beans
- Customer
- Customer data has to persist, thus it is
maintained in the database. - Customer data has to survive in the case of
server crash. - Customer data is shared by many clients.
- Each customer has unique identification such as
customer number.
18Differences Between the Session and Entity Beans
- Entity Beans
- Represent persistent data
- Long-lived
- Session Beans
- Interact with clients
- Model business Logic
- Short-lived
Session Bean
Entity Bean
Enterprise JavaBeans Container
Adapted from Dave Ellimans G53ELC slides,
http//www.cs.nott.ac.uk/dge/G53ELC/
19Differences Between the Session and Entity Beans
- Session Beans
- Represent a business process
- One instance per client
- Short-lived Life of client is life of bean
- Transient
- Doesnt survive server crashes
- May be transactional
- Entity Beans
- Represent business data
- Shared instance for multiple clients
- Long-lived as long as data in database
- Persistent
- Survive server crashes
- Always transactional
Source Sang Shin, Enterprise JavaBeans
20EJB Architecture
- In this section we look at both EJB2 and EJB3
architectures. - Complexity has been a major factor holding back
EJB adaption. - EJB 3.0 is an attempt to simplify enterprise java
development - EJB 2.0 component development and requirements
- EJB 3.0 component development
21Anatomy of an EJB2 Component
- A EJB2 module contains
- Interface classes (must be present)
- Home interface
- Remote interface
- Bean class (must be present)
- Deployment descriptor (must be present)
- Helper classes (present only when needed by Bean
class)
Source Sang Shin, Enterprise JavaBeans
22Anatomy of EJB 2.0 Module(EJB-JAR file)
Source Sang Shin, Enterprise JavaBeans
23An Example of ejb-jar File Layout in EJB 2.0
CatalogServer
CatalogServer.class
CatalogServerLocal.class
CatalogServerHome.class
CatalogServerLocalHome.class
CatalogServerBean.class
META-INF
ejb-jar.xml
24Deploying an EJB2 Component
- You need to know how to deploy the EJB to a
server. - You need to know how to find and use the bean
from a client. - EJB-JAR Deployment Descriptor
- Defines contract between producer and consumer of
ejb-jar file - It is an XML document that must be well formed
in XML sense and must be valid with respect to
the DTD given in EJB specification - stored with the name META-INF/ejb-jar.xml in the
ejb-jar file - Captures two basic kinds of information
- Structural and Application assembly information.
source Sang Shin, Enterprise JavaBeans,
http//www.jvapassion.com
25EJB2 - Home Interface
- EJB home interfaces are located by clients using
JNDI. - An EJB server publishes the home interface for a
particular EJB object under a particular name in
JNDI namespace. - The EJB client connects to JNDI server and looks
up the EJB home interface.
26Fundamental Steps an EJB Client Performs (in EJB2
model)
- Gets a JNDI context from the EJB/J2EE Server.
- Uses this context to look up a home interface for
the bean. - Uses the home interface to create (or find) a
reference to an EJB. - Calls methods on the bean.
27Example of EJB2 Client
- import javax.ejb.
- import javax.naming.
- import java.rmi.
- import java.util.Properties
- public class PersonClient
- public static void main(String args)
- String name args0
- try
- // Get a JNDI context for our EJB server
(EJBHome, in this case) - Properties p new Properties()
- p.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ejbhome.naming.spi.rmi.RMIInitCtxFactory")
- // Add URL, host or port options, if needed...
- Context context new InitialContext(p)
- // Get the home interface for Person beans
- PersonHome pHome
(PersonHome)context.lookup("People") - // Create a named person
-
Source Java Enterprise in a Nutshell by David
Flanagan et al
28Example of EJB2 Client (contd)
- Person person pHome.create(name)
- // Use the remote stub interface to access the
person's data . . . - catch (NoSuchPersonException nspe)
- System.out.println("Invalid person " name)
- catch (Exception e)
- System.out.println("Error while creating/using
person.") -
-
-
29EJB2 example Remote Client Interface
- import javax.ejb.
- import java.rmi.Remote
- import java.rmi.RemoteException
- public interface Person extends EJBObject
- public String getName() throws RemoteExeption
- public String setName() throws RemoteException
Source Java Enterprise in a Nutshell by David
Flanagan et al
30The Enterprise JavaBeans Object - EJB2
- To develop your own EJB object, you typically
need to provide three java interface/classes in
order to fully describe your EJB object - A bean interface (remote and/or local version)
- A home interface (remote and/or local version)
- An enterprise bean implementation
31Example
- A shopping cart EJB2 Component
The example is adapted from Bill Roth, An
Introduction to Enterprise JavaBeans Technology
32EJB 2.0 example - EJBHome
- public interface CartHome extends
javax.ejb.EJBHome - Cart create(String customerName, String account)
- throws RemoteException, BadAccountException
-
33EJB 2.0 example - the remote interface for the
Bean
public interface ShoppingCart extends
javax.ejb.EJBObject boolean addItem(int
itemNumber) throws java.rmi.RemoteException
boolean purchase() throws java.rmi.RemoteExcept
ion
34EJB 2.0 example - Implementation
public class ShoppingCartEJB implements
SessionBean Public boolean addItem(int
itemNumber) // the code for adding items to
the cart // may include JDBC code.
public boolean purchase () // the code for
purchases public ejbCreate(String
accountName, String account) // object
initialization code
35EJB 2.0 example - Client-side, Locating the
EJBHome object
Context initialContext new InitialContext()
CartHome cartHome (CartHome)
initialContext.lookup( "applications/mall/shoppi
ng-carts")
36EJB 2.0 example - Client-side, using the
EJBHome
ShoppingCartEJB cart cartHome.create("Emma",
"0507") cart.addItem(100) cart.addItem(251)
cart.purchase()
37EJBs component model
- Platform Independence
- EJB technology is a part of java technology.
- Middleware Independence
- Components designed to the EJB specification run
on all middleware solutions that implement the
EJB specification.
38EJB component model (contd)
- Preservation of Investment
- enterprise developers can use the benefits of
developing EJB technology-based applications and
also continue to use their existing middleware
solutions. - Ease of Development and Deployment
39EJBs component model (contd)
- Reusability and Portability
- EJB provides reusable and portable components
- EJBs server-side component architecture provides
an environment that hide the system level details
necessary to provide transactions, distributed
computing, persistence, and more from the eyes of
programmers, and allowed the programmers to
quickly build and deploy middleware-independent
applications.
40EJB 3.0
- Simplified programming model
- EJB 2.1 is too noisy
- Inherit javax.ejb
- Interface/implementation
- Strange combination of checked/unchecked
exceptions - Callback methods
- JNDI lookups
- Metadata XML hell
- Verbosity
- Lack of useful defaults
- Cant see code and metadata at the same time
Entity Beans in EJB3, Gavin King, JBoss Inc
41EJB 3.0 Goals
- Simplify Development
- EJB Plain Old Java Object (POJO)
- Use metadata annotations
- Reduce number of artifacts (Class, interface)
- Attract broad range of developers
- Standardize persistence API
- O-R Mapping similar to Oracle TopLink, JBoss,
Hibernate
EJB 3.0 and JSF Update, Sean Yeh, Oracle Taiwan
Corporation
42EJB3 Simplification
- POJO and POJI
- Removes complexity of earlier versions using
simple and familiar Java artifacts. - EJB Class will be a Plain Java class.
- EJB Interface does not have to implement
EJBObject. - No need for home interface.
- Annotation for type of EJB and interface.
EJB 3.0 and JSF Update, Sean Yeh, Oracle Taiwan
Corporation
43Session Beans in EJB3
- Plain java object plain java interface
- No home interface required
- Callback methods are optional
- Dependency injection
- Metadata as annotations
- Bean type, _at_Session, _at_Stateful, _at_MessageDriven
- Transaction attributes, _at_Transaction
- Dependency injection _at_Inject, _at_EJB, _at_Resource
- Remoteness _at_Remote, _at_Local, _at_WebService
- Remove method for stateful beans _at_Remove
Entity Beans in EJB3, Gavin King, JBoss Inc
44Annotation in Java 5
- Java 5 has introduced a program annotation
facility. - You can define custom annotations and then
annotate fields, methods, classes, etc. - Annotations do not directly affect program
semantics. - Tools can inspect the annotations to generated
additional structures (similar to a deployment
descriptor) or enforce specific runtime behaviour.
45Stateless Beans in EJB3
- It is very easy to create a Stateless Bean with
EJB 3.0. - All bean types do not implement any home
interface in EJB 3.0. - The class will be tagged as _at_Stateless. This
marks the class as a stateless bean and the
deployer will deploy that class as a stateless
bean EJB container.
46EJB 3.0 Session
import javax.ejb._at_Stateless_at_Remotepublic
class HelloWorldBean public String
sayHello() return "Hello World!!!"
EJB 3.0 and JSF Update, Sean Yeh, Oracle Taiwan
Corporation
47Another example Stateless Session Bean in EJB3
- import javax.ejb.Stateless
- _at_Stateless public class CalculatorBean implements
CalculatorRemote, CalculatorLocal - public int add(int x, int y)
- return x y
-
- public int subtract(int x, int y)
- return x - y
-
-
Source http//docs.jboss.org/ejb3/app-server/tuto
rial/stateless/stateless.html
48Stateless Session Bean in EJB3 -
CalculatorRemote.java
- import javax.ejb.Remote
- _at_Remote public interface CalculatorRemote extends
Calculator -
Source http//docs.jboss.org/ejb3/app-server/tuto
rial/stateless/stateless.html
49Stateless Session Bean in EJB3-
CalculatorLocal.java
- import javax.ejb.Local
- _at_Local public interface CalculatorLocal extends
Calculator -
Source http//docs.jboss.org/ejb3/app-server/tuto
rial/stateless/stateless.html
50Stateless Session Bean in EJB3 - the Client
- import javax.naming.InitialContext
- public class Client
- public static void main(String args) throws
Exception - InitialContext ctx new InitialContext()
- Calculator calculator (Calculator)
ctx.lookup("CalculatorBean/remote") - System.out.println("1 1 "
calculator.add(1, 1)) - System.out.println("1 - 1 "
calculator.subtract(1, 1)) -
-
Source http//docs.jboss.org/ejb3/app-server/tuto
rial/stateless/stateless.html
51Entity Beans in EJB3
- Plain Java Objects
- No required interfaces/inheritance
- All public methods nonfinal, all instance
variables private - Non-abstract persistent properties
- Public/protected get/set pair
- Or private instance variable
- Public/protected constructor with no arguments
- Identifier Version properties
- No home interface required
- Support for inheritance / polymorphism!
Entity Beans in EJB3, Gavin King, JBoss Inc
52Declaring an Entity Bean
- _at_Entity public class Flight implements
Serializable - Long id
- _at_Id public Long getId()
- return id
-
- public void setId(Long id)
- this.id id
-
-
53Do I Need an EJB Tier?
- Yes, if you want to leverage middleware features
provided by container - Resource management, instance life-cycle
management, - concurrency control and threading
- Persistence, transaction and security management
- Messaging, scalability, availability
- Yes, if you want to build portable and reusable
business components - Maybe not, for a simple application whose main
function is reading database tables. - Maybe not, if your application does not require
components to be distributed amongst different
servers.
Sang Shin, Enterprise JavaBeans, Sun
54Resources
- Sang Shin, EJB Overview, Sun Microsystems,
Inc. http//www.javapassion.com/ - Bill Roth, An Introduction to Enterprise
JavaBeans Technology. - Monica Pawlan, Writing Enterprise Applications
with Java 2 SDK, Enterprise Edition, Sun
Microsystems. - Java Enterprise in a Nutshell, Farley et al,
Chapter 8, OReilly.