SlideShare a Scribd company logo
Enterprise JavaBeans
Enterprise JavaBeans
Ruslana Svidzinska
Ruslana Svidzinska
CSE690
CSE690
What is EJB?
What is EJB?
 An EJB is a specialized, non-visual
An EJB is a specialized, non-visual
JavaBean that runs on a server.
JavaBean that runs on a server.
 EJB technology supports application
EJB technology supports application
development based on a multiplier,
development based on a multiplier,
distributed object architecture in
distributed object architecture in
which most of application’s logic is
which most of application’s logic is
moved from the client to the server.
moved from the client to the server.
Server Components
Server Components
 Server components are application
Server components are application
components that run in an
components that run in an
application server.
application server.
Java Application Servers
Java Application Servers
 A Java application server provides an
A Java application server provides an
optimized execution environment for
optimized execution environment for
server-side Java application
server-side Java application
components.
components.
 A Java application server delivers a
A Java application server delivers a
high-performance, highly scalable,
high-performance, highly scalable,
robust execution environment
robust execution environment
specifically suited to support Internet
specifically suited to support Internet
enabled application systems.
enabled application systems.
WORA
WORA
 The Enterprise JavaBeans
The Enterprise JavaBeans
architecture defines a standard
architecture defines a standard
model for Java application servers to
model for Java application servers to
support “Write Once, Run Anywhere”
support “Write Once, Run Anywhere”
(WORA) portability
(WORA) portability
Component Portability
Component Portability
EJB technology takes the WORA concept
EJB technology takes the WORA concept
to a new level.
to a new level.
EJB completely portable across any
EJB completely portable across any
vendor’s EJB compliant application
vendor’s EJB compliant application
server. The EJB environment
server. The EJB environment
automatically maps the component to
automatically maps the component to
the underlying vendor-specific
the underlying vendor-specific
infrastructure services.
infrastructure services.
Overview of EJB Technology
Overview of EJB Technology
Enterprise JavaBeans component model
logically extends the JavaBeans component
model to support server component.
Server components are reusable, prepackaged
pieces of application functionality that are
designed to run in an application server.
EJB can be assembled and customized at
deployment time using tools provided by an
EJB-compliant Java application server.
EJB Component Model
Simplifying Development.
Simplifying Development.
The EJB architecture provides an
integrated application framework.
An EJB server automatically manages a
number of tricky middleware services
on behalf of the application
components.
EJB component-builders can
concentrate on writing business logic
rather than complex middleware
Simplifying Development
Simplifying Development
(cont’d)
(cont’d)
RESULT:
•Application get developed more quickly
•Code is of better quality.
What EJB Accomplishes
What EJB Accomplishes
You can take any Java class and with little effort make it a
You can take any Java class and with little effort make it a
distributed
distributed,
, secure
secure,
, transactional
transactional class
class
You can take any data source and make the data source
You can take any data source and make the data source
appear to be a collection of Java objects
appear to be a collection of Java objects
– Eliminates distinction between data from a database
Eliminates distinction between data from a database
and any other source
and any other source
– All information is accessed through Java objects
All information is accessed through Java objects
– All SQL is cleanly encapsulated in Java objects
All SQL is cleanly encapsulated in Java objects

true object-oriented programming
true object-oriented programming

high reusability
high reusability
– Database objects work with the full Java class library
Database objects work with the full Java class library
What EJB Means to Us
What EJB Means to Us
 Developers can
Developers can focus on writing business logic
focus on writing business logic rather
rather
than writing low-level infrastructure like data access,
than writing low-level infrastructure like data access,
concurrency, transactions, threading, etc.
concurrency, transactions, threading, etc.
– Reduces development time
Reduces development time
– Reduces complexity
Reduces complexity
– Increases quality and reliability
Increases quality and reliability
 The knowledge about EJB is portable
The knowledge about EJB is portable among many
among many
different products because EJB products are based on a
different products because EJB products are based on a
common standard
common standard
 Greater
Greater reuse
reuse because code is located in shareable,
because code is located in shareable,
server objects
server objects
So....let’s take a look at
So....let’s take a look at
Enterprise JavaBeans
Enterprise JavaBeans
 A specification from JavaSoft
A specification from JavaSoft
 Enterprise JavaBeans defines a server component
Enterprise JavaBeans defines a server component
model for the development and deployment of Java
model for the development and deployment of Java
applications based on a multi-tier, distributed object
applications based on a multi-tier, distributed object
architecture
architecture
 The Enterprise JavaBeans specification defines:
The Enterprise JavaBeans specification defines:
– A container model
A container model
– A definition of the services the container needs to
A definition of the services the container needs to
provide to an Enterprise JavaBean, and vice versa
provide to an Enterprise JavaBean, and vice versa
– How a container should manage Enterprise
How a container should manage Enterprise
JavaBeans
JavaBeans
Enterprise JavaBeans
Enterprise JavaBeans
Architecture
Architecture
The EJB architecture specifies the
responsibilities and interactions among
EJB entities
 EJB Servers
 Enterprise Beans  EJB Clients
EJB Server
EJB Container
Enterprise
Bean
Enterprise
Bean
 EJB Containers
Clients
EJB Server
EJB Server
EJB Server
 The EJB Server provides system services and
The EJB Server provides system services and
manages resources
manages resources
– Process and thread management
Process and thread management
– System resources management
System resources management
– Database connection pooling and caching
Database connection pooling and caching
– Management API
Management API
Provides a Runtime Environment
EJB Server
EJB Container
EJB Container
EJB Container
 Hosts the Enterprise JavaBeans
Hosts the Enterprise JavaBeans
 Provides services to Enterprise JavaBeans
Provides services to Enterprise JavaBeans
– Naming
Naming
– Life cycle management
Life cycle management
– Persistence (state management)
Persistence (state management)
– Transaction Management
Transaction Management
– Security
Security
 Likely provided by server vendor
Likely provided by server vendor
Provides a Run-time Environment
for an Enterprise Bean
Enterprise JavaBeans
Enterprise JavaBeans
 A specialized Java class where the real business logic lives
A specialized Java class where the real business logic lives
– May be developer-written or tool-generated
May be developer-written or tool-generated
 Distributed over a network
Distributed over a network
 Transactional
Transactional
 Secure
Secure
 Server vendors provide tools that automatically generate
Server vendors provide tools that automatically generate
distribution, transaction and security behavior
distribution, transaction and security behavior
EJB Server
EJB Container
Enterprise
Bean
Enterprise
Bean
EJB Clients
EJB Clients
 Client access is controlled by the container in
Client access is controlled by the container in
which the enterprise Bean is deployed
which the enterprise Bean is deployed
 Clients locates an Enterprise JavaBean
Clients locates an Enterprise JavaBean
through Java Naming and Directory Interface
through Java Naming and Directory Interface
(JNDI)
(JNDI)
 RMI is the standard method for accessing a
RMI is the standard method for accessing a
bean over a network
bean over a network
EJB Server
EJB Container
Enterprise
Bean
Enterprise
Bean
Clients
What’s Unique About EJB
What’s Unique About EJB
 Mandates a container model where common services are declared,
Mandates a container model where common services are declared,
not programmed
not programmed
– At
At development and/or deployment time
development and/or deployment time, attributes defining the
, attributes defining the
bean’s transaction and security characteristics are specified
bean’s transaction and security characteristics are specified
– At
At deployment time
deployment time, the container introspects the Enterprise
, the container introspects the Enterprise
JavaBean attributes for the runtime services it requires and
JavaBean attributes for the runtime services it requires and
wraps the bean with the required functionality
wraps the bean with the required functionality
– At
At runtime
runtime, the container intercepts all calls to the object
, the container intercepts all calls to the object

Provides transactional, threading and security behavior required
Provides transactional, threading and security behavior required
before the method invocation
before the method invocation

Invokes the method on the object
Invokes the method on the object

Cleans up after the call
Cleans up after the call
Declarative Programming Model
Understanding EJB Components
Understanding EJB Components
JavaBeans vs Enterprise
JavaBeans vs Enterprise
JavaBeans
JavaBeans
 Enterprise JavaBeans is a framework for building
Enterprise JavaBeans is a framework for building
and deploying server-side Java components
and deploying server-side Java components
 JavaBeans is a framework for client-side Java
JavaBeans is a framework for client-side Java
components
components
 Conceptually related because both are
Conceptually related because both are
components
components
 The specifications are different
The specifications are different
 The specifications do not build on each other or
The specifications do not build on each other or
rely on each other
rely on each other
What’s in the EJB Specification
What’s in the EJB Specification
~200 Pages of technical material for EJB vendors
 Goals for the Release
Goals for the Release
 Roles and Scenarios
Roles and Scenarios
 Fundamentals (Scope of EJB)
Fundamentals (Scope of EJB)
 Session and Entity Beans
Session and Entity Beans
 Transactions, Exceptions, Distribution
Transactions, Exceptions, Distribution
 EJB Bean and Container Responsibilities
EJB Bean and Container Responsibilities
 API Reference
API Reference
EJB Vendors
Have to do all the WORK
Enterprise
Enterprise EJB
EJB Scenario
Scenario
Clients Web Server
EJB Application
Server
Existing
Enterprise
Middleware
CICS Programs
SAP Modules
Browser
Application
Servlet Shopping
Cart
Credit Card
Inventory
EJB Server
EJB Container
Databases
 Bean Class is written by the developer
Bean Class is written by the developer
 EJBHome and EJBObject interfaces and classes
EJBHome and EJBObject interfaces and classes
control access to the Bean class
control access to the Bean class
 Deployment Descriptor
Deployment Descriptor
and MANIFEST describe
and MANIFEST describe
security and transactional
security and transactional
characteristics of the Bean
characteristics of the Bean
Written by Developer
Generated at Deployment
Generated at Development
EJB Server
EJB Container
EJBHome
Interface
Deployment
Descriptor
EJBObject
Interface
EJBHome
Class
EJBObject
Class
EJB Class
Manifest
An inside look at the various
An inside look at the various
components of EJB
components of EJB
EJB Server
EJB Container
EJBHome
Interface
EJBHome
Class
EJBHome Interface and Class
EJBHome Interface and Class
 Used to get a reference to a bean’s remote interface
Used to get a reference to a bean’s remote interface
 Provides bean creation services
Provides bean creation services
– myFoo = fooHome.create() instead of
myFoo = fooHome.create() instead of
myFoo = new foo()
myFoo = new foo()
– Supports multiple signatures to create EJB instances
Supports multiple signatures to create EJB instances
 Similar to class factory
Similar to class factory
in COM and CORBA
in COM and CORBA
 May be generated by
May be generated by
tools that come with an
tools that come with an
EJB server
EJB server
 Also manages EJB:
Also manages EJB:
– querying (Entity Bean)
querying (Entity Bean)
– deleting (Entity Bean)
deleting (Entity Bean)
Interface javax.ejb.EJBHome
Interface javax.ejb.EJBHome
 Home objects must implement this interface
Home objects must implement this interface
 Returns a reference to a bean by creating or finding it
Returns a reference to a bean by creating or finding it
 Every bean has a EJBHome interface that provides
Every bean has a EJBHome interface that provides
methods for getting references to one or more beans
methods for getting references to one or more beans
– create methods are used to create new beans
create methods are used to create new beans
– there can be many create methods, similar to a
there can be many create methods, similar to a
class having many constructors
class having many constructors
 Provides a bean removal interface also
Provides a bean removal interface also
 The EJBHome Class implementation is provided by
The EJBHome Class implementation is provided by
the EJB Server Provider
the EJB Server Provider
Sample EJBHome Interface
Sample EJBHome Interface
public interface CustomerHome extends EJBHome
{
public abstract Customer create(String id, String name)
throws RemoteException, CreateException;
public abstract Enumeration findByName(String val)
throws RemoteException, FinderException;
public abstract RemoteEnumeration findStateByName(String val)
throws RemoteException, FinderException;
public abstract Customer findByPrimaryKey(CustomerKey pkey)
throws RemoteException, FinderException;
public abstract Customer findByPrimaryKey(CustomerKey pkey, int findSource)
throws RemoteException, FinderException;
public abstract CustomerState findStateByPrimaryKey(CustomerKey pkey, int
findSource)
throws RemoteException, FinderException;
}
Clients
EJB Server
EJB Container
EJBHom
e
Class
create()
Client makes invocation to
Client makes invocation to
EJBHome Class via the EJBHome
EJBHome Class via the EJBHome
Interface
Interface
 Client calls one of the create() methods on the
Client calls one of the create() methods on the
EJBHome Class. The EJBHome class can have
EJBHome Class. The EJBHome class can have
multiple create() signatures.
multiple create() signatures.
Clients
EJB Server
EJB Container
EJBHom
e
Class
EJB
Class
EJBHome Class instantiates
EJBHome Class instantiates
the Bean Class
the Bean Class
 When the create() method is
When the create() method is
called in the EJBHome Class, it
called in the EJBHome Class, it
is responsible for
is responsible for
instantiating the Bean class.
instantiating the Bean class.
EJB Server
EJB Container
EJBObject
Interface
EJBObject
Class
EJBObject Interface and
EJBObject Interface and
Class
Class
 Intercepts calls to the EJB Class to add support for:
Intercepts calls to the EJB Class to add support for:
– transactions
transactions
– security
security
– threading
threading
 EJBObject class has the same methods
EJBObject class has the same methods
as the bean and delegates to the bean
as the bean and delegates to the bean
for actual behavior
for actual behavior
 EJBObject class checks security and
EJBObject class checks security and
sets up transaction before delegating
sets up transaction before delegating
method call to the bean
method call to the bean
 Clients can never get a reference to
Clients can never get a reference to
a bean’s EJB Class, only the EJBObject
a bean’s EJB Class, only the EJBObject
interface
interface
Interface javax.ejb.EJBObject
Interface javax.ejb.EJBObject
public interface javax.ejb.EJBObject extends java.rmi.Remote
{
EJBHome getEJBHome() throws RemoteException;
Handle getHandle() throws RemoteException;
Object getPrimaryKey() throws RemoteException;
boolean isIdentical(EJBObject obj) throws RemoteException;
void remove() throws RemoteException, RemoveException;
}
 Represents a specific bean instance
Represents a specific bean instance
 Remote objects must implement this interface
Remote objects must implement this interface
 Primary key is an object that represents the primary key for a
Primary key is an object that represents the primary key for a
specific instance of a bean
specific instance of a bean
 The EJBObject Class implementation is provided by the EJB
The EJBObject Class implementation is provided by the EJB
Server Provider
Server Provider
Sample EJBObject Interface
Sample EJBObject Interface
public interface Customer extends EJBObject
{
public abstract String getId() throws RemoteException;
public abstract String getName() throws RemoteException;
public abstract void setName(String val) throws RemoteException;
public abstract boolean getNameNull() throws RemoteException;
public abstract boolean getIdNull() throws RemoteException;
public abstract Enumeration getAccounts() throws RemoteException;
public abstract void addToAccounts(Account relInst) throws RemoteException;
public abstract void removeFromAccounts(Account relInst)
throws RemoteException;
}
Clients
EJB Server
EJB Container
Passes ref
of Bean
Client now has reference
to the EJBObject Class.
NOT A REFERENCE
TO THE BEAN
ITSELF!!!!
EJBHome
Class
EJB
Class
EJBHome
Class
After the EJBHome Class
After the EJBHome Class
instantiates the Bean...
instantiates the Bean...
 The EJBHome Class will instantiate the EJBObject Class,
The EJBHome Class will instantiate the EJBObject Class,
initializing it with the remote object reference to the Bean
initializing it with the remote object reference to the Bean
Class.
Class.
 The Client will now
The Client will now
communicate to the
communicate to the
EJBObject Class.
EJBObject Class.
The EJBObject Class
The EJBObject Class
will delegate the call to
will delegate the call to
the Bean.
the Bean.
Clients
EJB Server
EJB Container
EJBHome
Class
EJB
Class
EJBHome
Class
Client communicates to the
Client communicates to the
Bean class via the EJBObject
Bean class via the EJBObject
Class
Class
 Client never has a direct reference to the Bean.
Client never has a direct reference to the Bean.
 The EJBObject Interface is the interface for the Bean,
The EJBObject Interface is the interface for the Bean,
so the EJBObject Class “delegates” the calls to the
so the EJBObject Class “delegates” the calls to the
Bean.
Bean.
 The EJBObject Class
The EJBObject Class
implementation will be
implementation will be
generated using vendor
generated using vendor
tools.
tools.
EJB Class
EJB Class
 A bean has a single Java class at its core
A bean has a single Java class at its core
– This class is written by a developer if it’s a session bean
This class is written by a developer if it’s a session bean
– This class is sometimes generated by a tool if it’s an
This class is sometimes generated by a tool if it’s an
entity bean
entity bean
 Implements application-specific business logic
Implements application-specific business logic
 Implements one of the following contracts:
Implements one of the following contracts:
– javax.ejb.EntityBean
javax.ejb.EntityBean
– javax.ejb.SessionBean
javax.ejb.SessionBean
 These contracts provide for consistent behavior when
These contracts provide for consistent behavior when
activating beans, passivating beans, reading data, writing
activating beans, passivating beans, reading data, writing
data
data
 Every container can expect these methods in every bean
Every container can expect these methods in every bean
Deployment
Descriptor
EJB Container
EJB Server
Deployment Descriptor
Deployment Descriptor
 Allows you to declare transaction and security attributes, NO
Allows you to declare transaction and security attributes, NO
PROGRAMMING REQUIRED!!!
PROGRAMMING REQUIRED!!!
 An EJB Deployment Descriptor describes the classes, interfaces and
An EJB Deployment Descriptor describes the classes, interfaces and
declarative behavior of an EJB
declarative behavior of an EJB
 Deployment Descriptor format is serialized objects:
Deployment Descriptor format is serialized objects:
– javax.ejb.deployment.ControlDescriptor
javax.ejb.deployment.ControlDescriptor
– javax.ejb.deployment.DeploymentDescriptor
javax.ejb.deployment.DeploymentDescriptor
– javax.ejb.deployment.EntityDescriptor
javax.ejb.deployment.EntityDescriptor
– javax.ejb.deployment.SessionDescriptor
javax.ejb.deployment.SessionDescriptor
 The deployment descriptor
The deployment descriptor
is generated by server tools
is generated by server tools
 The deployment descriptor
The deployment descriptor
classes are defined in the
classes are defined in the
EJB specification
EJB specification
Let’s look at the value of the
Let’s look at the value of the
Deployment Descriptor
Deployment Descriptor
 Step #1
Step #1 - Write your Bean implementation.
- Write your Bean implementation.
 Step #2
Step #2 - Compile this Java source into Java bytecode
- Compile this Java source into Java bytecode
 Step #3
Step #3 - Developer is responsible for creating a serialized
- Developer is responsible for creating a serialized
deployment descriptor for the bean. Most likely using a tool
deployment descriptor for the bean. Most likely using a tool
from the vendor. EJB tools will use Reflection API on the
from the vendor. EJB tools will use Reflection API on the
compiled EJB Bean to determine:
compiled EJB Bean to determine:
– name of Bean class
name of Bean class
– methods
methods
– parameters
parameters
– return values
return values
 Step #4
Step #4 - The EJB Tool will use the above information to
- The EJB Tool will use the above information to
generate a Deployment Descriptor file and an editor with
generate a Deployment Descriptor file and an editor with
which to set transaction and security attributes.
which to set transaction and security attributes.
Sample Contents of a
Sample Contents of a
Deployment Descriptor
Deployment Descriptor
PS(TicketDemo,Concert,deployment_descriptor)
Entity{
VersionNumber
{
1.0
}
BeanHomeName
{
ConcertHome
}
ControlDescriptor
{
IsolationLevel
{
TRANSACTION_READ_COMMITTED
}
Method
{
int getId() throws java.rmi.RemoteException
}
RunAsMode
{
SYSTEM_IDENTITY
}
TransactionAttribute
{
TX_SUPPORTS
}
Method Level
Security Attribute
Method Level
Transaction Attribute
Manifest
EJB Container
EJB Server
Enterprise JavaBean Packaging
Enterprise JavaBean Packaging
 Enterprise JavaBeans are comprised of many Java files
Enterprise JavaBeans are comprised of many Java files
 These files are put in a JAR file
These files are put in a JAR file
– A JAR file is a ZIP file with a MANIFEST that describes
A JAR file is a ZIP file with a MANIFEST that describes
the contents of the file
the contents of the file
– A MANIFEST is a simple text file
A MANIFEST is a simple text file

Name: bank/AccountDeployment.ser
Name: bank/AccountDeployment.ser
Enterprise-Bean: True
Enterprise-Bean: True
 A JAR file can contain more than one Enterprise JavaBean
A JAR file can contain more than one Enterprise JavaBean
Written by Developer
Generated at Development
Generated at Deployment EJB Server
EJB Container
EJBHome
Interface
Deployment
Descriptor
EJBObject
Interface
EJBHome
Class
EJBObject
Class
EJB Class
Manifest
Bean Development Process
Bean Development Process
 Implement the EJB Class
Implement the EJB Class
 Specify the remote interface
Specify the remote interface
 Specify the home interface
Specify the home interface
 Specify security and
Specify security and
transactional characteristics
transactional characteristics
using vendor tools
using vendor tools
(DeploymentDescriptor)
(DeploymentDescriptor)
 Use vendor tools to
Use vendor tools to
generate supporting
generate supporting
code and package
code and package
components in EJB-jar
components in EJB-jar
 Iterate...
Iterate...
Enterprise Beans:
Enterprise Beans:
Session Beans & Entity Beans
Session Beans & Entity Beans
Session Beans vs. Entity Beans
Session Beans vs. Entity Beans
Bean-Managed Persistence
Bean-Managed Persistence
Container-Managed Persistence
Container-Managed Persistence
EJB Transaction Attributes
EJB Transaction Attributes
Comparing Session and
Comparing Session and
Entity Beans
Entity Beans
 Mandatory for EJB 1.0
Mandatory for EJB 1.0
 Represents a specific
Represents a specific
client
client
(1 instance per client)
(1 instance per client)
 Short-lived
Short-lived
 Transient
Transient
 Can be any Java class
Can be any Java class
 May be transactional
May be transactional
 Business Logic Beans
Business Logic Beans
 Optional for EJB 1.0
Optional for EJB 1.0
 Represents underlying data
Represents underlying data
object or context
object or context
(clients share instance)
(clients share instance)
 Long-lived
Long-lived
 Persistent
Persistent
 Can be a class that maps to
Can be a class that maps to
persistent data
persistent data
(e.g., database)
(e.g., database)
 Always transactional
Always transactional
 Beans which represent data
Beans which represent data
Session Beans
Session Beans Entity Beans
Entity Beans
Session Beans
Session Beans
Represents
Represents Process
Process
 A transient agent for an individual client that executes
A transient agent for an individual client that executes
on a server (e.g., ShoppingCart)
on a server (e.g., ShoppingCart)
 Session beans are often a client of multiple entity beans
Session beans are often a client of multiple entity beans

Implements
Implements javax.ejb.SessionBean
javax.ejb.SessionBean interface
interface
 State management types for session EJBs
State management types for session EJBs
– stateful - session bean may maintain state information across
stateful - session bean may maintain state information across
method calls
method calls
– stateless - session bean may be used to service multiple clients
stateless - session bean may be used to service multiple clients
– a stateless session bean can only have a single no-argument
a stateless session bean can only have a single no-argument
create() method in its Home interface
create() method in its Home interface
Session Beans - Stateful or
Session Beans - Stateful or
Stateless
Stateless
 A Stateful Session Bean maintains a one-to-one relationship with a
A Stateful Session Bean maintains a one-to-one relationship with a
Client. It maintains a user “session”. Most common example is an e-
Client. It maintains a user “session”. Most common example is an e-
commerce application with a “shopping cart” unique for each user.
commerce application with a “shopping cart” unique for each user.
– Container will automatically “swap out” the Session bean if it is inactive. Here the container
Container will automatically “swap out” the Session bean if it is inactive. Here the container
calls the ejbPassivate() method to save any private data to some physical storage.
calls the ejbPassivate() method to save any private data to some physical storage.
– When container receives new request, the Container will call the ejbActivate() method to
When container receives new request, the Container will call the ejbActivate() method to
restore the Session Bean.
restore the Session Bean.
 A Stateless Session Bean can be accessed by multiple incoming clients
A Stateless Session Bean can be accessed by multiple incoming clients
and keeps no private data. It does not maintain a unique session with
and keeps no private data. It does not maintain a unique session with
a client.
a client.
– Keeps no persistent data. If it crashes, container simply starts another one and the client
Keeps no persistent data. If it crashes, container simply starts another one and the client
transparently connects.
transparently connects.
– All access to the Bean is serialized.
All access to the Bean is serialized.
Entity Bean
Entity Bean
Represents
Represents Data
Data
 Implements
Implements javax.ejb.EntityBean
javax.ejb.EntityBean interface
interface
 Maps a data source to a Java class
Maps a data source to a Java class
– table, view, join or stored procedure in a relational database
table, view, join or stored procedure in a relational database
– a set of related records in a database
a set of related records in a database
– legacy data
legacy data
 Each instance of an entity bean is one row of data
Each instance of an entity bean is one row of data
 Each instance of an entity bean is uniquely identified by
Each instance of an entity bean is uniquely identified by
a primary key
a primary key
 An Entity Bean can also have additional methods for
An Entity Bean can also have additional methods for
business logic, etc.
business logic, etc.
Defining an Entity Bean
Defining an Entity Bean
 An Entity Bean must implement the javax.ejb.EntityBean
An Entity Bean must implement the javax.ejb.EntityBean
interface. In addition, the Entity Bean must implement an
interface. In addition, the Entity Bean must implement an
ejbCreate() method for each create() method on the Home
ejbCreate() method for each create() method on the Home
Interface.
Interface.
 When the Home class gets a call to create(), it calls the
When the Home class gets a call to create(), it calls the
ejbCreate() method on the Entity Bean with the
ejbCreate() method on the Entity Bean with the
corresponding signature.
corresponding signature.
 ejbStore() and ejbLoad() used to synchronize Entity Bean
ejbStore() and ejbLoad() used to synchronize Entity Bean
data with the database.
data with the database.
 ejbActivate() and ejbPassivate() used for notification that
ejbActivate() and ejbPassivate() used for notification that
Entity Bean state is being written to the database or
Entity Bean state is being written to the database or
restored from the database.
restored from the database.
Since Entity Beans represent
Since Entity Beans represent
Data...
Data...
 Each instance of an Entity Bean is
Each instance of an Entity Bean is
uniquely identified by a primary key
uniquely identified by a primary key
object
object
 Primary key can be saved and used
Primary key can be saved and used
later to regain access to the same EJB
later to regain access to the same EJB
object identity
object identity
– fooKey = fooBean.getPrimaryKey();
fooKey = fooBean.getPrimaryKey();
…
…
fooBean = fooHome.findByPrimaryKey(fooKey);
fooBean = fooHome.findByPrimaryKey(fooKey);
Entity Bean Operations
Entity Bean Operations
 Bean
BeanHome.create() is equivalent to an SQL INSERT
Home.create() is equivalent to an SQL INSERT
– Causes a new database record to be inserted into
Causes a new database record to be inserted into
the database:
the database:

customerBean = customerHome.create(”Jane",
customerBean = customerHome.create(”Jane",
”Rodgers");
”Rodgers");
 Bean
BeanHome.find
Home.findSomething
Something() is equivalent to an SQL
() is equivalent to an SQL
SELECT
SELECT
– Creates a bean instance that represents queried data from
Creates a bean instance that represents queried data from
a database
a database
– Can also return an enumeration to represent multiple rows
Can also return an enumeration to represent multiple rows
of data
of data
 There will typically be many find
There will typically be many findSomething
Something() methods:
() methods:

customerBean =
customerBean =
customerHome.findByName(firstName, lastName);
customerHome.findByName(firstName, lastName);

customerBeans = customerHome.findByZip(94023);
customerBeans = customerHome.findByZip(94023);
Entity Bean Operations
Entity Bean Operations
 Bean
BeanHome.remove() and EJBObject.remove()
Home.remove() and EJBObject.remove()
are equivalent to an SQL DELETE
are equivalent to an SQL DELETE
– causes the database record to be deleted from the
causes the database record to be deleted from the
database
database

customerBean = customerHome.findByName(“Jane”,
customerBean = customerHome.findByName(“Jane”,
“Rodgers”);
“Rodgers”);
customerBean.remove();
customerBean.remove();
 Commiting a change on a found object is
Commiting a change on a found object is
equivalent to an SQL UPDATE
equivalent to an SQL UPDATE

customerBean = customerHome.findByName(“Jane”,
customerBean = customerHome.findByName(“Jane”,
“Rodgers”);
“Rodgers”);
customerBean.setEmailAddress(“jane.rodgers@yahoo.com”);
customerBean.setEmailAddress(“jane.rodgers@yahoo.com”);
EJB Persistence
EJB Persistence
 Provides Entity Beans the ability to
Provides Entity Beans the ability to
store and retrieve their state
store and retrieve their state
 Can be implemented by a bean
Can be implemented by a bean
– Bean Managed Persistence
Bean Managed Persistence
 Can be implemented by a container
Can be implemented by a container
– Container Managed Persistence
Container Managed Persistence
Bean Managed Persistence
Bean Managed Persistence
 The entity bean is responsible for its persistent behavior
The entity bean is responsible for its persistent behavior
 EJB developer must implement database access
EJB developer must implement database access
– ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()
ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()
 Not automated, developer manually creates mapping
Not automated, developer manually creates mapping
through JDBC calls
through JDBC calls
 Not as reusable
Not as reusable
– Hard-code database access within class
Hard-code database access within class
 Advanced features like connection pooling and caching
Advanced features like connection pooling and caching
are difficult to support because of reliance on hand
are difficult to support because of reliance on hand
written code
written code
Container Managed
Container Managed
Persistence
Persistence
 The EJB container is responsible for persistence
The EJB container is responsible for persistence
 The container provides tools that generate
The container provides tools that generate
code in the EJB class that maps methods in the
code in the EJB class that maps methods in the
bean to a result set
bean to a result set
– Can map to a table, view, join or stored procedure in a
Can map to a table, view, join or stored procedure in a
database
database
– Server provides automated mapping to convert relational data
Server provides automated mapping to convert relational data
to bean instances
to bean instances
 Advanced features like connection pooling and
Advanced features like connection pooling and
caching are easily supported
caching are easily supported
 High reuse
High reuse
EJB Transaction Support
EJB Transaction Support
 EJB allows you to either DECLARE transactions or CODE THEM
EJB allows you to either DECLARE transactions or CODE THEM
EXPLICITLY.
EXPLICITLY.
– TO DECLARE
TO DECLARE: EJB allows you to declare transaction support in the
: EJB allows you to declare transaction support in the
Deployment Descriptor and then have the container take care of
Deployment Descriptor and then have the container take care of
the details inside the remote class
the details inside the remote class

Transaction attributes specified at the bean and method level
Transaction attributes specified at the bean and method level
– FOR EXPLICIT CONTROL
FOR EXPLICIT CONTROL: An EJB Container is required to
: An EJB Container is required to
implement
implement javax.transaction.UserTransaction
javax.transaction.UserTransaction

Provides an interface to a transaction service
Provides an interface to a transaction service

Can be used by EJB clients and enterprise beans that are declared to
Can be used by EJB clients and enterprise beans that are declared to
manage their own transactions (TX_BEAN_MANAGED)
manage their own transactions (TX_BEAN_MANAGED)
– EJB specification does not support nested transactions
EJB specification does not support nested transactions
EJB Transaction Attributes
EJB Transaction Attributes
 TX_NOT_SUPPORTED
TX_NOT_SUPPORTED
– Cannot execute within a transaction
Cannot execute within a transaction
– Suspends any existing transaction while method is called
Suspends any existing transaction while method is called
 TX_SUPPORTS
TX_SUPPORTS
– Executes with or without a transaction
Executes with or without a transaction
– Doesn’t suspend existing transaction
Doesn’t suspend existing transaction
 TX_REQUIRED
TX_REQUIRED
– Executes within a transaction
Executes within a transaction
– If no transaction exists, starts a new one and commits it when method completes
If no transaction exists, starts a new one and commits it when method completes
 TX_REQUIRES_NEW
TX_REQUIRES_NEW
– Always starts a new transaction and commits it when method completes
Always starts a new transaction and commits it when method completes
– Suspends existing transaction
Suspends existing transaction
 TX_BEAN_MANAGED
TX_BEAN_MANAGED
– The bean manages its own transaction control
The bean manages its own transaction control
– Suspends existing transaction
Suspends existing transaction
 TX_MANDATORY
TX_MANDATORY
– Must execute within a transaction
Must execute within a transaction
– If no transaction exists, throws the TransactionRequiredException
If no transaction exists, throws the TransactionRequiredException

More Related Content

PPT
Ejb course in-mumbai
PPT
Ejb (1)
PPTX
The Latest in Enterprise JavaBeans Technology
PDF
Ejb notes
PPT
Aravind vinnakota ejb_architecture
PDF
Summer training java
PPT
Summer training java
PPTX
Ejb and jsp
Ejb course in-mumbai
Ejb (1)
The Latest in Enterprise JavaBeans Technology
Ejb notes
Aravind vinnakota ejb_architecture
Summer training java
Summer training java
Ejb and jsp

Similar to ejb.ppt java lecture notes enterprise java (20)

PPTX
Ejbandjsp 200119145750
PDF
EJB 3.0 - Yet Another Introduction
PDF
Java Introduction
PPT
Enterprise application developement
PPT
Virtual classroom
PDF
Introcution to EJB
PPT
Unite5-EJB-2019.ppt
PPT
Introduction to java ee
PPTX
Advance java1.1
PDF
EJ NOV-18 (Sol) (E-next.in).pdf
PPTX
Advanced Java Programming - Enterprise Java Beans client
PPT
ADVANCED JAVA MODULE I & II.ppt
PDF
Real world java_ee_patterns
PPT
Greate Introduction to Oracle Fusion Middleware and ADF
PPTX
Devjyotippt
PPT
Introduction to java_ee
PPTX
4. J2EE.pptx
PPTX
Web programming and development - Introduction
PDF
Java Platform and IDE Netbeans 6.7 for Developing Enterprise and Web Applicat...
Ejbandjsp 200119145750
EJB 3.0 - Yet Another Introduction
Java Introduction
Enterprise application developement
Virtual classroom
Introcution to EJB
Unite5-EJB-2019.ppt
Introduction to java ee
Advance java1.1
EJ NOV-18 (Sol) (E-next.in).pdf
Advanced Java Programming - Enterprise Java Beans client
ADVANCED JAVA MODULE I & II.ppt
Real world java_ee_patterns
Greate Introduction to Oracle Fusion Middleware and ADF
Devjyotippt
Introduction to java_ee
4. J2EE.pptx
Web programming and development - Introduction
Java Platform and IDE Netbeans 6.7 for Developing Enterprise and Web Applicat...
Ad

More from kavitamittal18 (20)

PPT
awt.ppt java windows programming lecture
PPT
pptTopic2IntroductionToJavaProgramming.ppt
PPT
11MappingDesigntoCode.ppt Software engineering
PPT
UseCase.ppt software engineering use3 cases
PPT
11MappingDesigntoCode.ppt ooad software software
PPT
Introduction.ppt wireless
PPT
CellularNetworks.ppt ppt
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
PPT
CSL101_Ch1.ppt Computer Science
PPT
maincse-150510153437-lva1-app68Computer Science92.ppt
PPT
Programming language basics.ppt Computer Science
PPT
02-chapter-1.ppt programming languages 10
PPT
CS553_ST7_Ch14-CellularWirelessNetworks.ppt
PPT
Lec7!JavaThreads.ppt java multithreading
PPT
JDBC.ppt database connectivity in java ppt
PPT
chapter7.ppt java programming lecture notes
PPT
09slide.ppt oops classes and objects concept
PPT
480 GPS Tech mobile computing presentation
PPT
gsm-archtecture.ppt mobile computing ppt
PPT
AdHocTutorial.ppt
awt.ppt java windows programming lecture
pptTopic2IntroductionToJavaProgramming.ppt
11MappingDesigntoCode.ppt Software engineering
UseCase.ppt software engineering use3 cases
11MappingDesigntoCode.ppt ooad software software
Introduction.ppt wireless
CellularNetworks.ppt ppt
Dr.C S Prasanth-Physics ppt.pptx computer
CSL101_Ch1.ppt Computer Science
maincse-150510153437-lva1-app68Computer Science92.ppt
Programming language basics.ppt Computer Science
02-chapter-1.ppt programming languages 10
CS553_ST7_Ch14-CellularWirelessNetworks.ppt
Lec7!JavaThreads.ppt java multithreading
JDBC.ppt database connectivity in java ppt
chapter7.ppt java programming lecture notes
09slide.ppt oops classes and objects concept
480 GPS Tech mobile computing presentation
gsm-archtecture.ppt mobile computing ppt
AdHocTutorial.ppt
Ad

Recently uploaded (20)

PPTX
Current and future trends in Computer Vision.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Artificial Intelligence
PPT
Project quality management in manufacturing
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Current and future trends in Computer Vision.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
additive manufacturing of ss316l using mig welding
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
OOP with Java - Java Introduction (Basics)
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
CH1 Production IntroductoryConcepts.pptx
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
CYBER-CRIMES AND SECURITY A guide to understanding
Artificial Intelligence
Project quality management in manufacturing
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Geodesy 1.pptx...............................................
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Construction Project Organization Group 2.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...

ejb.ppt java lecture notes enterprise java

  • 1. Enterprise JavaBeans Enterprise JavaBeans Ruslana Svidzinska Ruslana Svidzinska CSE690 CSE690
  • 2. What is EJB? What is EJB?  An EJB is a specialized, non-visual An EJB is a specialized, non-visual JavaBean that runs on a server. JavaBean that runs on a server.  EJB technology supports application EJB technology supports application development based on a multiplier, development based on a multiplier, distributed object architecture in distributed object architecture in which most of application’s logic is which most of application’s logic is moved from the client to the server. moved from the client to the server.
  • 3. Server Components Server Components  Server components are application Server components are application components that run in an components that run in an application server. application server.
  • 4. Java Application Servers Java Application Servers  A Java application server provides an A Java application server provides an optimized execution environment for optimized execution environment for server-side Java application server-side Java application components. components.  A Java application server delivers a A Java application server delivers a high-performance, highly scalable, high-performance, highly scalable, robust execution environment robust execution environment specifically suited to support Internet specifically suited to support Internet enabled application systems. enabled application systems.
  • 5. WORA WORA  The Enterprise JavaBeans The Enterprise JavaBeans architecture defines a standard architecture defines a standard model for Java application servers to model for Java application servers to support “Write Once, Run Anywhere” support “Write Once, Run Anywhere” (WORA) portability (WORA) portability
  • 6. Component Portability Component Portability EJB technology takes the WORA concept EJB technology takes the WORA concept to a new level. to a new level. EJB completely portable across any EJB completely portable across any vendor’s EJB compliant application vendor’s EJB compliant application server. The EJB environment server. The EJB environment automatically maps the component to automatically maps the component to the underlying vendor-specific the underlying vendor-specific infrastructure services. infrastructure services.
  • 7. Overview of EJB Technology Overview of EJB Technology Enterprise JavaBeans component model logically extends the JavaBeans component model to support server component. Server components are reusable, prepackaged pieces of application functionality that are designed to run in an application server. EJB can be assembled and customized at deployment time using tools provided by an EJB-compliant Java application server. EJB Component Model
  • 8. Simplifying Development. Simplifying Development. The EJB architecture provides an integrated application framework. An EJB server automatically manages a number of tricky middleware services on behalf of the application components. EJB component-builders can concentrate on writing business logic rather than complex middleware
  • 10. What EJB Accomplishes What EJB Accomplishes You can take any Java class and with little effort make it a You can take any Java class and with little effort make it a distributed distributed, , secure secure, , transactional transactional class class You can take any data source and make the data source You can take any data source and make the data source appear to be a collection of Java objects appear to be a collection of Java objects – Eliminates distinction between data from a database Eliminates distinction between data from a database and any other source and any other source – All information is accessed through Java objects All information is accessed through Java objects – All SQL is cleanly encapsulated in Java objects All SQL is cleanly encapsulated in Java objects  true object-oriented programming true object-oriented programming  high reusability high reusability – Database objects work with the full Java class library Database objects work with the full Java class library
  • 11. What EJB Means to Us What EJB Means to Us  Developers can Developers can focus on writing business logic focus on writing business logic rather rather than writing low-level infrastructure like data access, than writing low-level infrastructure like data access, concurrency, transactions, threading, etc. concurrency, transactions, threading, etc. – Reduces development time Reduces development time – Reduces complexity Reduces complexity – Increases quality and reliability Increases quality and reliability  The knowledge about EJB is portable The knowledge about EJB is portable among many among many different products because EJB products are based on a different products because EJB products are based on a common standard common standard  Greater Greater reuse reuse because code is located in shareable, because code is located in shareable, server objects server objects
  • 12. So....let’s take a look at So....let’s take a look at Enterprise JavaBeans Enterprise JavaBeans  A specification from JavaSoft A specification from JavaSoft  Enterprise JavaBeans defines a server component Enterprise JavaBeans defines a server component model for the development and deployment of Java model for the development and deployment of Java applications based on a multi-tier, distributed object applications based on a multi-tier, distributed object architecture architecture  The Enterprise JavaBeans specification defines: The Enterprise JavaBeans specification defines: – A container model A container model – A definition of the services the container needs to A definition of the services the container needs to provide to an Enterprise JavaBean, and vice versa provide to an Enterprise JavaBean, and vice versa – How a container should manage Enterprise How a container should manage Enterprise JavaBeans JavaBeans
  • 13. Enterprise JavaBeans Enterprise JavaBeans Architecture Architecture The EJB architecture specifies the responsibilities and interactions among EJB entities  EJB Servers  Enterprise Beans  EJB Clients EJB Server EJB Container Enterprise Bean Enterprise Bean  EJB Containers Clients
  • 14. EJB Server EJB Server EJB Server  The EJB Server provides system services and The EJB Server provides system services and manages resources manages resources – Process and thread management Process and thread management – System resources management System resources management – Database connection pooling and caching Database connection pooling and caching – Management API Management API Provides a Runtime Environment
  • 15. EJB Server EJB Container EJB Container EJB Container  Hosts the Enterprise JavaBeans Hosts the Enterprise JavaBeans  Provides services to Enterprise JavaBeans Provides services to Enterprise JavaBeans – Naming Naming – Life cycle management Life cycle management – Persistence (state management) Persistence (state management) – Transaction Management Transaction Management – Security Security  Likely provided by server vendor Likely provided by server vendor Provides a Run-time Environment for an Enterprise Bean
  • 16. Enterprise JavaBeans Enterprise JavaBeans  A specialized Java class where the real business logic lives A specialized Java class where the real business logic lives – May be developer-written or tool-generated May be developer-written or tool-generated  Distributed over a network Distributed over a network  Transactional Transactional  Secure Secure  Server vendors provide tools that automatically generate Server vendors provide tools that automatically generate distribution, transaction and security behavior distribution, transaction and security behavior EJB Server EJB Container Enterprise Bean Enterprise Bean
  • 17. EJB Clients EJB Clients  Client access is controlled by the container in Client access is controlled by the container in which the enterprise Bean is deployed which the enterprise Bean is deployed  Clients locates an Enterprise JavaBean Clients locates an Enterprise JavaBean through Java Naming and Directory Interface through Java Naming and Directory Interface (JNDI) (JNDI)  RMI is the standard method for accessing a RMI is the standard method for accessing a bean over a network bean over a network EJB Server EJB Container Enterprise Bean Enterprise Bean Clients
  • 18. What’s Unique About EJB What’s Unique About EJB  Mandates a container model where common services are declared, Mandates a container model where common services are declared, not programmed not programmed – At At development and/or deployment time development and/or deployment time, attributes defining the , attributes defining the bean’s transaction and security characteristics are specified bean’s transaction and security characteristics are specified – At At deployment time deployment time, the container introspects the Enterprise , the container introspects the Enterprise JavaBean attributes for the runtime services it requires and JavaBean attributes for the runtime services it requires and wraps the bean with the required functionality wraps the bean with the required functionality – At At runtime runtime, the container intercepts all calls to the object , the container intercepts all calls to the object  Provides transactional, threading and security behavior required Provides transactional, threading and security behavior required before the method invocation before the method invocation  Invokes the method on the object Invokes the method on the object  Cleans up after the call Cleans up after the call Declarative Programming Model
  • 20. JavaBeans vs Enterprise JavaBeans vs Enterprise JavaBeans JavaBeans  Enterprise JavaBeans is a framework for building Enterprise JavaBeans is a framework for building and deploying server-side Java components and deploying server-side Java components  JavaBeans is a framework for client-side Java JavaBeans is a framework for client-side Java components components  Conceptually related because both are Conceptually related because both are components components  The specifications are different The specifications are different  The specifications do not build on each other or The specifications do not build on each other or rely on each other rely on each other
  • 21. What’s in the EJB Specification What’s in the EJB Specification ~200 Pages of technical material for EJB vendors  Goals for the Release Goals for the Release  Roles and Scenarios Roles and Scenarios  Fundamentals (Scope of EJB) Fundamentals (Scope of EJB)  Session and Entity Beans Session and Entity Beans  Transactions, Exceptions, Distribution Transactions, Exceptions, Distribution  EJB Bean and Container Responsibilities EJB Bean and Container Responsibilities  API Reference API Reference EJB Vendors Have to do all the WORK
  • 22. Enterprise Enterprise EJB EJB Scenario Scenario Clients Web Server EJB Application Server Existing Enterprise Middleware CICS Programs SAP Modules Browser Application Servlet Shopping Cart Credit Card Inventory EJB Server EJB Container Databases
  • 23.  Bean Class is written by the developer Bean Class is written by the developer  EJBHome and EJBObject interfaces and classes EJBHome and EJBObject interfaces and classes control access to the Bean class control access to the Bean class  Deployment Descriptor Deployment Descriptor and MANIFEST describe and MANIFEST describe security and transactional security and transactional characteristics of the Bean characteristics of the Bean Written by Developer Generated at Deployment Generated at Development EJB Server EJB Container EJBHome Interface Deployment Descriptor EJBObject Interface EJBHome Class EJBObject Class EJB Class Manifest An inside look at the various An inside look at the various components of EJB components of EJB
  • 24. EJB Server EJB Container EJBHome Interface EJBHome Class EJBHome Interface and Class EJBHome Interface and Class  Used to get a reference to a bean’s remote interface Used to get a reference to a bean’s remote interface  Provides bean creation services Provides bean creation services – myFoo = fooHome.create() instead of myFoo = fooHome.create() instead of myFoo = new foo() myFoo = new foo() – Supports multiple signatures to create EJB instances Supports multiple signatures to create EJB instances  Similar to class factory Similar to class factory in COM and CORBA in COM and CORBA  May be generated by May be generated by tools that come with an tools that come with an EJB server EJB server  Also manages EJB: Also manages EJB: – querying (Entity Bean) querying (Entity Bean) – deleting (Entity Bean) deleting (Entity Bean)
  • 25. Interface javax.ejb.EJBHome Interface javax.ejb.EJBHome  Home objects must implement this interface Home objects must implement this interface  Returns a reference to a bean by creating or finding it Returns a reference to a bean by creating or finding it  Every bean has a EJBHome interface that provides Every bean has a EJBHome interface that provides methods for getting references to one or more beans methods for getting references to one or more beans – create methods are used to create new beans create methods are used to create new beans – there can be many create methods, similar to a there can be many create methods, similar to a class having many constructors class having many constructors  Provides a bean removal interface also Provides a bean removal interface also  The EJBHome Class implementation is provided by The EJBHome Class implementation is provided by the EJB Server Provider the EJB Server Provider
  • 26. Sample EJBHome Interface Sample EJBHome Interface public interface CustomerHome extends EJBHome { public abstract Customer create(String id, String name) throws RemoteException, CreateException; public abstract Enumeration findByName(String val) throws RemoteException, FinderException; public abstract RemoteEnumeration findStateByName(String val) throws RemoteException, FinderException; public abstract Customer findByPrimaryKey(CustomerKey pkey) throws RemoteException, FinderException; public abstract Customer findByPrimaryKey(CustomerKey pkey, int findSource) throws RemoteException, FinderException; public abstract CustomerState findStateByPrimaryKey(CustomerKey pkey, int findSource) throws RemoteException, FinderException; }
  • 27. Clients EJB Server EJB Container EJBHom e Class create() Client makes invocation to Client makes invocation to EJBHome Class via the EJBHome EJBHome Class via the EJBHome Interface Interface  Client calls one of the create() methods on the Client calls one of the create() methods on the EJBHome Class. The EJBHome class can have EJBHome Class. The EJBHome class can have multiple create() signatures. multiple create() signatures.
  • 28. Clients EJB Server EJB Container EJBHom e Class EJB Class EJBHome Class instantiates EJBHome Class instantiates the Bean Class the Bean Class  When the create() method is When the create() method is called in the EJBHome Class, it called in the EJBHome Class, it is responsible for is responsible for instantiating the Bean class. instantiating the Bean class.
  • 29. EJB Server EJB Container EJBObject Interface EJBObject Class EJBObject Interface and EJBObject Interface and Class Class  Intercepts calls to the EJB Class to add support for: Intercepts calls to the EJB Class to add support for: – transactions transactions – security security – threading threading  EJBObject class has the same methods EJBObject class has the same methods as the bean and delegates to the bean as the bean and delegates to the bean for actual behavior for actual behavior  EJBObject class checks security and EJBObject class checks security and sets up transaction before delegating sets up transaction before delegating method call to the bean method call to the bean  Clients can never get a reference to Clients can never get a reference to a bean’s EJB Class, only the EJBObject a bean’s EJB Class, only the EJBObject interface interface
  • 30. Interface javax.ejb.EJBObject Interface javax.ejb.EJBObject public interface javax.ejb.EJBObject extends java.rmi.Remote { EJBHome getEJBHome() throws RemoteException; Handle getHandle() throws RemoteException; Object getPrimaryKey() throws RemoteException; boolean isIdentical(EJBObject obj) throws RemoteException; void remove() throws RemoteException, RemoveException; }  Represents a specific bean instance Represents a specific bean instance  Remote objects must implement this interface Remote objects must implement this interface  Primary key is an object that represents the primary key for a Primary key is an object that represents the primary key for a specific instance of a bean specific instance of a bean  The EJBObject Class implementation is provided by the EJB The EJBObject Class implementation is provided by the EJB Server Provider Server Provider
  • 31. Sample EJBObject Interface Sample EJBObject Interface public interface Customer extends EJBObject { public abstract String getId() throws RemoteException; public abstract String getName() throws RemoteException; public abstract void setName(String val) throws RemoteException; public abstract boolean getNameNull() throws RemoteException; public abstract boolean getIdNull() throws RemoteException; public abstract Enumeration getAccounts() throws RemoteException; public abstract void addToAccounts(Account relInst) throws RemoteException; public abstract void removeFromAccounts(Account relInst) throws RemoteException; }
  • 32. Clients EJB Server EJB Container Passes ref of Bean Client now has reference to the EJBObject Class. NOT A REFERENCE TO THE BEAN ITSELF!!!! EJBHome Class EJB Class EJBHome Class After the EJBHome Class After the EJBHome Class instantiates the Bean... instantiates the Bean...  The EJBHome Class will instantiate the EJBObject Class, The EJBHome Class will instantiate the EJBObject Class, initializing it with the remote object reference to the Bean initializing it with the remote object reference to the Bean Class. Class.  The Client will now The Client will now communicate to the communicate to the EJBObject Class. EJBObject Class. The EJBObject Class The EJBObject Class will delegate the call to will delegate the call to the Bean. the Bean.
  • 33. Clients EJB Server EJB Container EJBHome Class EJB Class EJBHome Class Client communicates to the Client communicates to the Bean class via the EJBObject Bean class via the EJBObject Class Class  Client never has a direct reference to the Bean. Client never has a direct reference to the Bean.  The EJBObject Interface is the interface for the Bean, The EJBObject Interface is the interface for the Bean, so the EJBObject Class “delegates” the calls to the so the EJBObject Class “delegates” the calls to the Bean. Bean.  The EJBObject Class The EJBObject Class implementation will be implementation will be generated using vendor generated using vendor tools. tools.
  • 34. EJB Class EJB Class  A bean has a single Java class at its core A bean has a single Java class at its core – This class is written by a developer if it’s a session bean This class is written by a developer if it’s a session bean – This class is sometimes generated by a tool if it’s an This class is sometimes generated by a tool if it’s an entity bean entity bean  Implements application-specific business logic Implements application-specific business logic  Implements one of the following contracts: Implements one of the following contracts: – javax.ejb.EntityBean javax.ejb.EntityBean – javax.ejb.SessionBean javax.ejb.SessionBean  These contracts provide for consistent behavior when These contracts provide for consistent behavior when activating beans, passivating beans, reading data, writing activating beans, passivating beans, reading data, writing data data  Every container can expect these methods in every bean Every container can expect these methods in every bean
  • 35. Deployment Descriptor EJB Container EJB Server Deployment Descriptor Deployment Descriptor  Allows you to declare transaction and security attributes, NO Allows you to declare transaction and security attributes, NO PROGRAMMING REQUIRED!!! PROGRAMMING REQUIRED!!!  An EJB Deployment Descriptor describes the classes, interfaces and An EJB Deployment Descriptor describes the classes, interfaces and declarative behavior of an EJB declarative behavior of an EJB  Deployment Descriptor format is serialized objects: Deployment Descriptor format is serialized objects: – javax.ejb.deployment.ControlDescriptor javax.ejb.deployment.ControlDescriptor – javax.ejb.deployment.DeploymentDescriptor javax.ejb.deployment.DeploymentDescriptor – javax.ejb.deployment.EntityDescriptor javax.ejb.deployment.EntityDescriptor – javax.ejb.deployment.SessionDescriptor javax.ejb.deployment.SessionDescriptor  The deployment descriptor The deployment descriptor is generated by server tools is generated by server tools  The deployment descriptor The deployment descriptor classes are defined in the classes are defined in the EJB specification EJB specification
  • 36. Let’s look at the value of the Let’s look at the value of the Deployment Descriptor Deployment Descriptor  Step #1 Step #1 - Write your Bean implementation. - Write your Bean implementation.  Step #2 Step #2 - Compile this Java source into Java bytecode - Compile this Java source into Java bytecode  Step #3 Step #3 - Developer is responsible for creating a serialized - Developer is responsible for creating a serialized deployment descriptor for the bean. Most likely using a tool deployment descriptor for the bean. Most likely using a tool from the vendor. EJB tools will use Reflection API on the from the vendor. EJB tools will use Reflection API on the compiled EJB Bean to determine: compiled EJB Bean to determine: – name of Bean class name of Bean class – methods methods – parameters parameters – return values return values  Step #4 Step #4 - The EJB Tool will use the above information to - The EJB Tool will use the above information to generate a Deployment Descriptor file and an editor with generate a Deployment Descriptor file and an editor with which to set transaction and security attributes. which to set transaction and security attributes.
  • 37. Sample Contents of a Sample Contents of a Deployment Descriptor Deployment Descriptor PS(TicketDemo,Concert,deployment_descriptor) Entity{ VersionNumber { 1.0 } BeanHomeName { ConcertHome } ControlDescriptor { IsolationLevel { TRANSACTION_READ_COMMITTED } Method { int getId() throws java.rmi.RemoteException } RunAsMode { SYSTEM_IDENTITY } TransactionAttribute { TX_SUPPORTS } Method Level Security Attribute Method Level Transaction Attribute
  • 38. Manifest EJB Container EJB Server Enterprise JavaBean Packaging Enterprise JavaBean Packaging  Enterprise JavaBeans are comprised of many Java files Enterprise JavaBeans are comprised of many Java files  These files are put in a JAR file These files are put in a JAR file – A JAR file is a ZIP file with a MANIFEST that describes A JAR file is a ZIP file with a MANIFEST that describes the contents of the file the contents of the file – A MANIFEST is a simple text file A MANIFEST is a simple text file  Name: bank/AccountDeployment.ser Name: bank/AccountDeployment.ser Enterprise-Bean: True Enterprise-Bean: True  A JAR file can contain more than one Enterprise JavaBean A JAR file can contain more than one Enterprise JavaBean
  • 39. Written by Developer Generated at Development Generated at Deployment EJB Server EJB Container EJBHome Interface Deployment Descriptor EJBObject Interface EJBHome Class EJBObject Class EJB Class Manifest Bean Development Process Bean Development Process  Implement the EJB Class Implement the EJB Class  Specify the remote interface Specify the remote interface  Specify the home interface Specify the home interface  Specify security and Specify security and transactional characteristics transactional characteristics using vendor tools using vendor tools (DeploymentDescriptor) (DeploymentDescriptor)  Use vendor tools to Use vendor tools to generate supporting generate supporting code and package code and package components in EJB-jar components in EJB-jar  Iterate... Iterate...
  • 40. Enterprise Beans: Enterprise Beans: Session Beans & Entity Beans Session Beans & Entity Beans Session Beans vs. Entity Beans Session Beans vs. Entity Beans Bean-Managed Persistence Bean-Managed Persistence Container-Managed Persistence Container-Managed Persistence EJB Transaction Attributes EJB Transaction Attributes
  • 41. Comparing Session and Comparing Session and Entity Beans Entity Beans  Mandatory for EJB 1.0 Mandatory for EJB 1.0  Represents a specific Represents a specific client client (1 instance per client) (1 instance per client)  Short-lived Short-lived  Transient Transient  Can be any Java class Can be any Java class  May be transactional May be transactional  Business Logic Beans Business Logic Beans  Optional for EJB 1.0 Optional for EJB 1.0  Represents underlying data Represents underlying data object or context object or context (clients share instance) (clients share instance)  Long-lived Long-lived  Persistent Persistent  Can be a class that maps to Can be a class that maps to persistent data persistent data (e.g., database) (e.g., database)  Always transactional Always transactional  Beans which represent data Beans which represent data Session Beans Session Beans Entity Beans Entity Beans
  • 42. Session Beans Session Beans Represents Represents Process Process  A transient agent for an individual client that executes A transient agent for an individual client that executes on a server (e.g., ShoppingCart) on a server (e.g., ShoppingCart)  Session beans are often a client of multiple entity beans Session beans are often a client of multiple entity beans  Implements Implements javax.ejb.SessionBean javax.ejb.SessionBean interface interface  State management types for session EJBs State management types for session EJBs – stateful - session bean may maintain state information across stateful - session bean may maintain state information across method calls method calls – stateless - session bean may be used to service multiple clients stateless - session bean may be used to service multiple clients – a stateless session bean can only have a single no-argument a stateless session bean can only have a single no-argument create() method in its Home interface create() method in its Home interface
  • 43. Session Beans - Stateful or Session Beans - Stateful or Stateless Stateless  A Stateful Session Bean maintains a one-to-one relationship with a A Stateful Session Bean maintains a one-to-one relationship with a Client. It maintains a user “session”. Most common example is an e- Client. It maintains a user “session”. Most common example is an e- commerce application with a “shopping cart” unique for each user. commerce application with a “shopping cart” unique for each user. – Container will automatically “swap out” the Session bean if it is inactive. Here the container Container will automatically “swap out” the Session bean if it is inactive. Here the container calls the ejbPassivate() method to save any private data to some physical storage. calls the ejbPassivate() method to save any private data to some physical storage. – When container receives new request, the Container will call the ejbActivate() method to When container receives new request, the Container will call the ejbActivate() method to restore the Session Bean. restore the Session Bean.  A Stateless Session Bean can be accessed by multiple incoming clients A Stateless Session Bean can be accessed by multiple incoming clients and keeps no private data. It does not maintain a unique session with and keeps no private data. It does not maintain a unique session with a client. a client. – Keeps no persistent data. If it crashes, container simply starts another one and the client Keeps no persistent data. If it crashes, container simply starts another one and the client transparently connects. transparently connects. – All access to the Bean is serialized. All access to the Bean is serialized.
  • 44. Entity Bean Entity Bean Represents Represents Data Data  Implements Implements javax.ejb.EntityBean javax.ejb.EntityBean interface interface  Maps a data source to a Java class Maps a data source to a Java class – table, view, join or stored procedure in a relational database table, view, join or stored procedure in a relational database – a set of related records in a database a set of related records in a database – legacy data legacy data  Each instance of an entity bean is one row of data Each instance of an entity bean is one row of data  Each instance of an entity bean is uniquely identified by Each instance of an entity bean is uniquely identified by a primary key a primary key  An Entity Bean can also have additional methods for An Entity Bean can also have additional methods for business logic, etc. business logic, etc.
  • 45. Defining an Entity Bean Defining an Entity Bean  An Entity Bean must implement the javax.ejb.EntityBean An Entity Bean must implement the javax.ejb.EntityBean interface. In addition, the Entity Bean must implement an interface. In addition, the Entity Bean must implement an ejbCreate() method for each create() method on the Home ejbCreate() method for each create() method on the Home Interface. Interface.  When the Home class gets a call to create(), it calls the When the Home class gets a call to create(), it calls the ejbCreate() method on the Entity Bean with the ejbCreate() method on the Entity Bean with the corresponding signature. corresponding signature.  ejbStore() and ejbLoad() used to synchronize Entity Bean ejbStore() and ejbLoad() used to synchronize Entity Bean data with the database. data with the database.  ejbActivate() and ejbPassivate() used for notification that ejbActivate() and ejbPassivate() used for notification that Entity Bean state is being written to the database or Entity Bean state is being written to the database or restored from the database. restored from the database.
  • 46. Since Entity Beans represent Since Entity Beans represent Data... Data...  Each instance of an Entity Bean is Each instance of an Entity Bean is uniquely identified by a primary key uniquely identified by a primary key object object  Primary key can be saved and used Primary key can be saved and used later to regain access to the same EJB later to regain access to the same EJB object identity object identity – fooKey = fooBean.getPrimaryKey(); fooKey = fooBean.getPrimaryKey(); … … fooBean = fooHome.findByPrimaryKey(fooKey); fooBean = fooHome.findByPrimaryKey(fooKey);
  • 47. Entity Bean Operations Entity Bean Operations  Bean BeanHome.create() is equivalent to an SQL INSERT Home.create() is equivalent to an SQL INSERT – Causes a new database record to be inserted into Causes a new database record to be inserted into the database: the database:  customerBean = customerHome.create(”Jane", customerBean = customerHome.create(”Jane", ”Rodgers"); ”Rodgers");  Bean BeanHome.find Home.findSomething Something() is equivalent to an SQL () is equivalent to an SQL SELECT SELECT – Creates a bean instance that represents queried data from Creates a bean instance that represents queried data from a database a database – Can also return an enumeration to represent multiple rows Can also return an enumeration to represent multiple rows of data of data  There will typically be many find There will typically be many findSomething Something() methods: () methods:  customerBean = customerBean = customerHome.findByName(firstName, lastName); customerHome.findByName(firstName, lastName);  customerBeans = customerHome.findByZip(94023); customerBeans = customerHome.findByZip(94023);
  • 48. Entity Bean Operations Entity Bean Operations  Bean BeanHome.remove() and EJBObject.remove() Home.remove() and EJBObject.remove() are equivalent to an SQL DELETE are equivalent to an SQL DELETE – causes the database record to be deleted from the causes the database record to be deleted from the database database  customerBean = customerHome.findByName(“Jane”, customerBean = customerHome.findByName(“Jane”, “Rodgers”); “Rodgers”); customerBean.remove(); customerBean.remove();  Commiting a change on a found object is Commiting a change on a found object is equivalent to an SQL UPDATE equivalent to an SQL UPDATE  customerBean = customerHome.findByName(“Jane”, customerBean = customerHome.findByName(“Jane”, “Rodgers”); “Rodgers”); customerBean.setEmailAddress(“jane.rodgers@yahoo.com”); customerBean.setEmailAddress(“jane.rodgers@yahoo.com”);
  • 49. EJB Persistence EJB Persistence  Provides Entity Beans the ability to Provides Entity Beans the ability to store and retrieve their state store and retrieve their state  Can be implemented by a bean Can be implemented by a bean – Bean Managed Persistence Bean Managed Persistence  Can be implemented by a container Can be implemented by a container – Container Managed Persistence Container Managed Persistence
  • 50. Bean Managed Persistence Bean Managed Persistence  The entity bean is responsible for its persistent behavior The entity bean is responsible for its persistent behavior  EJB developer must implement database access EJB developer must implement database access – ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove() ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()  Not automated, developer manually creates mapping Not automated, developer manually creates mapping through JDBC calls through JDBC calls  Not as reusable Not as reusable – Hard-code database access within class Hard-code database access within class  Advanced features like connection pooling and caching Advanced features like connection pooling and caching are difficult to support because of reliance on hand are difficult to support because of reliance on hand written code written code
  • 51. Container Managed Container Managed Persistence Persistence  The EJB container is responsible for persistence The EJB container is responsible for persistence  The container provides tools that generate The container provides tools that generate code in the EJB class that maps methods in the code in the EJB class that maps methods in the bean to a result set bean to a result set – Can map to a table, view, join or stored procedure in a Can map to a table, view, join or stored procedure in a database database – Server provides automated mapping to convert relational data Server provides automated mapping to convert relational data to bean instances to bean instances  Advanced features like connection pooling and Advanced features like connection pooling and caching are easily supported caching are easily supported  High reuse High reuse
  • 52. EJB Transaction Support EJB Transaction Support  EJB allows you to either DECLARE transactions or CODE THEM EJB allows you to either DECLARE transactions or CODE THEM EXPLICITLY. EXPLICITLY. – TO DECLARE TO DECLARE: EJB allows you to declare transaction support in the : EJB allows you to declare transaction support in the Deployment Descriptor and then have the container take care of Deployment Descriptor and then have the container take care of the details inside the remote class the details inside the remote class  Transaction attributes specified at the bean and method level Transaction attributes specified at the bean and method level – FOR EXPLICIT CONTROL FOR EXPLICIT CONTROL: An EJB Container is required to : An EJB Container is required to implement implement javax.transaction.UserTransaction javax.transaction.UserTransaction  Provides an interface to a transaction service Provides an interface to a transaction service  Can be used by EJB clients and enterprise beans that are declared to Can be used by EJB clients and enterprise beans that are declared to manage their own transactions (TX_BEAN_MANAGED) manage their own transactions (TX_BEAN_MANAGED) – EJB specification does not support nested transactions EJB specification does not support nested transactions
  • 53. EJB Transaction Attributes EJB Transaction Attributes  TX_NOT_SUPPORTED TX_NOT_SUPPORTED – Cannot execute within a transaction Cannot execute within a transaction – Suspends any existing transaction while method is called Suspends any existing transaction while method is called  TX_SUPPORTS TX_SUPPORTS – Executes with or without a transaction Executes with or without a transaction – Doesn’t suspend existing transaction Doesn’t suspend existing transaction  TX_REQUIRED TX_REQUIRED – Executes within a transaction Executes within a transaction – If no transaction exists, starts a new one and commits it when method completes If no transaction exists, starts a new one and commits it when method completes  TX_REQUIRES_NEW TX_REQUIRES_NEW – Always starts a new transaction and commits it when method completes Always starts a new transaction and commits it when method completes – Suspends existing transaction Suspends existing transaction  TX_BEAN_MANAGED TX_BEAN_MANAGED – The bean manages its own transaction control The bean manages its own transaction control – Suspends existing transaction Suspends existing transaction  TX_MANDATORY TX_MANDATORY – Must execute within a transaction Must execute within a transaction – If no transaction exists, throws the TransactionRequiredException If no transaction exists, throws the TransactionRequiredException