Enterprise JavaBeans Ruslana Svidzinska CSE690. What is EJB? l An EJB is a specialized, non-visual...
-
date post
18-Dec-2015 -
Category
Documents
-
view
220 -
download
3
Transcript of Enterprise JavaBeans Ruslana Svidzinska CSE690. What is EJB? l An EJB is a specialized, non-visual...
Enterprise JavaBeansEnterprise JavaBeans
Ruslana SvidzinskaRuslana Svidzinska
CSE690CSE690
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 EJB technology supports application development based on application development based on a multiplier, distributed object a multiplier, distributed object architecture in which most of architecture in which most of application’s logic is moved from application’s logic is moved from the client to the server. the client to the server.
Server ComponentsServer 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 ServersJava 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.
WORAWORA
The Enterprise JavaBeans The Enterprise JavaBeans architecture defines a standard architecture defines a standard model for Java application servers model for Java application servers to support “Write Once, Run to support “Write Once, Run Anywhere” (WORA) portability Anywhere” (WORA) portability
Component PortabilityComponent Portability
EJB technology takes the WORA EJB technology takes the WORA concept to a new level.concept 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 automatically maps the component to the underlying vendor-specific to the underlying vendor-specific infrastructure services.infrastructure services.
Overview of EJB Overview of EJB TechnologyTechnology
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 AccomplishesWhat EJB Accomplishes
You can take any Java class and with little effort make it You can take any Java class and with little effort make it a a distributeddistributed, , securesecure, , transactionaltransactional 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 objectsappear to be a collection of Java objects
– Eliminates distinction between data from a database Eliminates distinction between data from a database and any other sourceand any other source
– All information is accessed through Java objectsAll information is accessed through Java objects– All SQL is cleanly encapsulated in Java objectsAll SQL is cleanly encapsulated in Java objects
true object-oriented programmingtrue object-oriented programming high reusabilityhigh reusability
– Database objects work with the full Java class libraryDatabase objects work with the full Java class library
What EJB Means to UsWhat EJB Means to Us
Developers can Developers can focus on writing business logicfocus on writing business logic rather than writing low-level infrastructure like data rather than writing low-level infrastructure like data access, concurrency, transactions, threading, etc. access, concurrency, transactions, threading, etc. – Reduces development timeReduces development time– Reduces complexityReduces complexity– Increases quality and reliabilityIncreases quality and reliability
The knowledge about EJB is portableThe knowledge about EJB is portable among among many different products because EJB products are many different products because EJB products are based on a common standardbased on a common standard
Greater Greater reusereuse because code is located in shareable, because code is located in shareable, server objectsserver objects
So....let’s take a look at So....let’s take a look at Enterprise JavaBeansEnterprise JavaBeans
A specification from JavaSoftA 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 architecturearchitecture
The Enterprise JavaBeans specification defines:The Enterprise JavaBeans specification defines:– A container modelA 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 versaprovide to an Enterprise JavaBean, and vice versa– How a container should manage Enterprise How a container should manage Enterprise
JavaBeansJavaBeans
Enterprise JavaBeans Enterprise JavaBeans ArchitectureArchitecture
The EJB architecture specifies the responsibilities and interactions among EJB entities
EJB Servers
Enterprise Beans EJB Clients
EJB ServerEJB Server
EJB Container
Enterprise Bean
Enterprise Bean
EJB Containers
Clients
EJB ServerEJB Server
EJB ServerEJB Server
The EJB Server provides system services and The EJB Server provides system services and manages resourcesmanages resources– Process and thread managementProcess and thread management– System resources managementSystem resources management– Database connection pooling and cachingDatabase connection pooling and caching– Management APIManagement API
Provides a Runtime EnvironmentProvides a Runtime Environment
EJB ServerEJB Server
EJB Container
EJB ContainerEJB Container
Hosts the Enterprise JavaBeansHosts the Enterprise JavaBeans Provides services to Enterprise JavaBeansProvides services to Enterprise JavaBeans
– NamingNaming– Life cycle managementLife cycle management– Persistence (state management)Persistence (state management)– Transaction ManagementTransaction Management– SecuritySecurity
Likely provided by server vendorLikely provided by server vendor
Provides a Run-time Environment for an Enterprise Bean
Provides a Run-time Environment for an Enterprise Bean
Enterprise JavaBeansEnterprise JavaBeans A specialized Java class where the real business logic A specialized Java class where the real business logic
liveslives– May be developer-written or tool-generatedMay be developer-written or tool-generated
Distributed over a networkDistributed over a network TransactionalTransactional SecureSecure Server vendors provide tools that automatically generate Server vendors provide tools that automatically generate
distribution, transaction and security behaviordistribution, transaction and security behavior
EJB ServerEJB Server
EJB Container
Enterprise Bean
Enterprise Bean
EJB ClientsEJB Clients
Client access is controlled by the container Client access is controlled by the container in which the enterprise Bean is deployedin which the enterprise Bean is deployed
Clients locates an Enterprise JavaBean Clients locates an Enterprise JavaBean through Java Naming and Directory through Java Naming and Directory Interface (JNDI)Interface (JNDI)
RMI is the standard method for accessing a RMI is the standard method for accessing a bean over a networkbean over a network
EJB ServerEJB Server
EJB Container
Enterprise Bean
Enterprise Bean
Clients
What’s Unique About EJBWhat’s Unique About EJB
Mandates a container model where common services are Mandates a container model where common services are declared, not programmeddeclared, not programmed– AtAt development and/or deployment timedevelopment and/or deployment time, attributes defining , attributes defining
the bean’s transaction and security characteristics are the bean’s transaction and security characteristics are specifiedspecified
– AtAt deployment timedeployment 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 functionalitywraps the bean with the required functionality
– AtAt runtimeruntime, 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 invocationbefore the method invocation Invokes the method on the objectInvokes the method on the object Cleans up after the callCleans up after the call
Declarative Programming ModelDeclarative Programming Model
Understanding EJB Understanding EJB ComponentsComponents
JavaBeans vs Enterprise JavaBeans vs Enterprise JavaBeansJavaBeans
Enterprise JavaBeans is a framework for Enterprise JavaBeans is a framework for building and deploying server-side Java building and deploying server-side Java componentscomponents
JavaBeans is a framework for client-side Java JavaBeans is a framework for client-side Java componentscomponents
Conceptually related because both are Conceptually related because both are componentscomponents
The specifications are differentThe specifications are different The specifications do not build on each other The specifications do not build on each other
or rely on each otheror rely on each other
What’s in the EJB What’s in the EJB SpecificationSpecification
~200 Pages of technical material for EJB vendors Goals for the ReleaseGoals for the Release Roles and ScenariosRoles and Scenarios Fundamentals (Scope of EJB)Fundamentals (Scope of EJB) Session and Entity BeansSession and Entity Beans Transactions, Exceptions, DistributionTransactions, Exceptions, Distribution EJB Bean and Container ResponsibilitiesEJB Bean and Container Responsibilities API ReferenceAPI Reference
EJB VendorsHave to do all the WORK
EnterpriseEnterprise EJBEJB ScenarioScenario
Clients Web ServerEJB Application
Server
ExistingEnterpriseMiddleware
CICS Programs
SAP Modules
Browser
Application
Servlet ShoppingCart
Credit Card
Inventory
EJB Server
EJB Container
Databases
Bean Class is written by the developerBean Class is written by the developer EJBHome and EJBObject interfaces and classes EJBHome and EJBObject interfaces and classes
control access to the Bean classcontrol access to the Bean class Deployment DescriptorDeployment Descriptor
and MANIFEST describeand MANIFEST describesecurity and transactionalsecurity and transactionalcharacteristics of the Beancharacteristics of the Bean
Written by Developer
Generated at Deployment
Generated at Development
EJB Server
EJB Container
EJ
BH
om
e
Inte
rfa
ce
EJ
BH
om
e
Inte
rfa
ce
Deployment Descriptor
Deployment Descriptor
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BH
om
eC
las
sE
JB
Ho
me
Cla
ss
EJB
Ob
ject
C
lass
EJB
Ob
ject
C
lass
EJB ClassEJB Class
ManifestManifest
An inside look at the An inside look at the various components of EJBvarious components of EJB
EJB Server
EJB Container
EJ
BH
om
e
Inte
rfa
ce
EJ
BH
om
e
Inte
rfa
ce
EJ
BH
om
eC
las
sE
JB
Ho
me
Cla
ss
EJBHome Interface and EJBHome Interface and ClassClass
Used to get a reference to a bean’s remote interfaceUsed to get a reference to a bean’s remote interface Provides bean creation servicesProvides bean creation services
– myFoo = fooHome.create() instead ofmyFoo = fooHome.create() instead ofmyFoo = new foo()myFoo = new foo()
– Supports multiple signatures to create EJB instancesSupports multiple signatures to create EJB instances Similar to class factorySimilar to class factory
in COM and CORBAin COM and CORBA May be generated byMay be generated by
tools that come with antools that come with anEJB serverEJB server
Also manages EJB:Also manages EJB:– querying (Entity Bean)querying (Entity Bean)– deleting (Entity Bean)deleting (Entity Bean)
Interface Interface javax.ejb.EJBHomejavax.ejb.EJBHome
Home objects must implement this interfaceHome objects must implement this interface Returns a reference to a bean by creating or finding itReturns 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 beansmethods for getting references to one or more beans– create methods are used to create new beanscreate 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 constructorsclass having many constructors Provides a bean removal interface alsoProvides a bean removal interface also The EJBHome Class implementation is provided by The EJBHome Class implementation is provided by
the EJB Server Providerthe EJB Server Provider
Sample EJBHome InterfaceSample 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
EJB
Ho
me
Cla
ss
create()
Client makes invocation to Client makes invocation to EJBHome Class via the EJBHome EJBHome Class via the EJBHome
InterfaceInterface
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
EJB
Ho
me
Cla
ss
EJB ClassEJB Class
EJBHome Class EJBHome Class instantiates instantiates
the Bean Classthe Bean Class When the create() method When the create() method
is called in the EJBHome is called in the EJBHome Class, it is responsible for Class, it is responsible for instantiating the Bean instantiating the Bean class.class.
EJB Server
EJB Container
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BO
bje
ct
Cla
ss
EJ
BO
bje
ct
Cla
ss
EJBObject Interface and EJBObject Interface and ClassClass
Intercepts calls to the EJB Class to add support for:Intercepts calls to the EJB Class to add support for:– transactionstransactions– securitysecurity– threadingthreading
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 behaviorfor 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 beanmethod 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 EJBObjecta bean’s EJB Class, only the EJBObjectinterfaceinterface
Interface Interface javax.ejb.EJBObjectjavax.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 instanceRepresents a specific bean instance Remote objects must implement this interfaceRemote objects must implement this interface Primary key is an object that represents the primary key Primary key is an object that represents the primary key
for a specific instance of a beanfor a specific instance of a bean The EJBObject Class implementation is provided by The EJBObject Class implementation is provided by
the EJB Server Providerthe EJB Server Provider
Sample EJBObject Sample EJBObject InterfaceInterface
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!!!!E
JBH
om
e C
lass
EJB ClassEJB Class
EJB
Ho
me
Cla
ss
After the EJBHome Class After the EJBHome Class instantiates the Bean...instantiates the Bean...
The EJBHome Class will instantiate the EJBObject The EJBHome Class will instantiate the EJBObject Class, initializing it with the remote object reference Class, initializing it with the remote object reference to the Bean Class.to the Bean Class.
The Client will nowThe Client will nowcommunicate to thecommunicate to theEJBObject Class. EJBObject Class. The EJBObject ClassThe EJBObject Classwill delegate the call towill delegate the call tothe Bean.the Bean.
Clients
EJB Server
EJB Container
EJB
Ho
me
Cla
ss
EJB ClassEJB Class
EJB
Ho
me
Cla
ss
Client communicates to the Client communicates to the Bean class via the EJBObject Bean class via the EJBObject
ClassClass 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 The EJBObject Interface is the interface for the
Bean, so the EJBObject Class “delegates” the Bean, so the EJBObject Class “delegates” the calls to the Bean.calls to the Bean.
The EJBObject ClassThe EJBObject Classimplementation will beimplementation will begenerated using vendorgenerated using vendortools.tools.
EJB ClassEJB Class A bean has a single Java class at its coreA bean has a single Java class at its core
– This class is written by a developer if it’s a session This class is written by a developer if it’s a session beanbean
– 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 beanentity bean
Implements application-specific business logicImplements application-specific business logic Implements one of the following contracts:Implements one of the following contracts:
– javax.ejb.EntityBeanjavax.ejb.EntityBean– javax.ejb.SessionBeanjavax.ejb.SessionBean
These contracts provide for consistent behavior when These contracts provide for consistent behavior when activating beans, passivating beans, reading data, activating beans, passivating beans, reading data, writing datawriting data
Every container can expect these methods in every Every container can expect these methods in every beanbean
Deployment Descriptor
Deployment Descriptor
EJB Container
EJB Server
Deployment DescriptorDeployment 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, An EJB Deployment Descriptor describes the classes,
interfaces and declarative behavior of an EJBinterfaces and declarative behavior of an EJB Deployment Descriptor format is serialized objects:Deployment Descriptor format is serialized objects:
– javax.ejb.deployment.ControlDescriptorjavax.ejb.deployment.ControlDescriptor– javax.ejb.deployment.DeploymentDescriptorjavax.ejb.deployment.DeploymentDescriptor– javax.ejb.deployment.EntityDescriptorjavax.ejb.deployment.EntityDescriptor– javax.ejb.deployment.SessionDescriptorjavax.ejb.deployment.SessionDescriptor
The deployment descriptor The deployment descriptor is generated by server toolsis generated by server tools
The deployment descriptor The deployment descriptor classes are defined in the classes are defined in the EJB specificationEJB specification
Let’s look at the value of the Let’s look at the value of the Deployment DescriptorDeployment Descriptor
Step #1Step #1 - Write your Bean implementation. - Write your Bean implementation. Step #2Step #2 - Compile this Java source into Java bytecode - Compile this Java source into Java bytecode Step #3Step #3 - Developer is responsible for creating a - Developer is responsible for creating a
serialized deployment descriptor for the bean. Most serialized deployment descriptor for the bean. Most likely using a tool from the vendor. EJB tools will use likely using a tool from the vendor. EJB tools will use Reflection API on the compiled EJB Bean to determine:Reflection API on the compiled EJB Bean to determine:– name of Bean classname of Bean class– methods methods – parametersparameters– return valuesreturn values
Step #4Step #4 - The EJB Tool will use the above information - The EJB Tool will use the above information to generate a Deployment Descriptor file and an editor to generate a Deployment Descriptor file and an editor with which to set transaction and security attributes.with which to set transaction and security attributes.
Sample Contents of a Sample Contents of a Deployment DescriptorDeployment 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
ManifestManifest
EJB Container
EJB Server
Enterprise JavaBean Enterprise JavaBean PackagingPackaging
Enterprise JavaBeans are comprised of many Java filesEnterprise JavaBeans are comprised of many Java files These files are put in a JAR fileThese files are put in a JAR file
– A JAR file is a ZIP file with a MANIFEST that A JAR file is a ZIP file with a MANIFEST that describes the contents of the filedescribes the contents of the file
– A MANIFEST is a simple text fileA MANIFEST is a simple text file Name: bank/AccountDeployment.serName: bank/AccountDeployment.serEnterprise-Bean: TrueEnterprise-Bean: True
A JAR file can contain more than one Enterprise A JAR file can contain more than one Enterprise JavaBeanJavaBean
Written by Developer
Generated at Development
Generated at Deployment EJB Server
EJB Container
EJ
BH
om
e
Inte
rfa
ce
EJ
BH
om
e
Inte
rfa
ce
Deployment Descriptor
Deployment Descriptor
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BO
bje
ct
Inte
rfa
ce
EJ
BH
om
eC
las
sE
JB
Ho
me
Cla
ss
EJ
BO
bje
ct
Cla
ss
EJ
BO
bje
ct
Cla
ss
EJB ClassEJB Class
ManifestManifest
Bean Development ProcessBean Development Process
Implement the EJB ClassImplement the EJB Class Specify the remote interfaceSpecify the remote interface Specify the home interfaceSpecify the home interface Specify security and Specify security and
transactional characteristicstransactional characteristicsusing vendor toolsusing vendor tools(DeploymentDescriptor)(DeploymentDescriptor)
Use vendor tools toUse vendor tools togenerate supportinggenerate supportingcode and packagecode and packagecomponents in EJB-jarcomponents in EJB-jar
Iterate... Iterate...
Enterprise Beans: Enterprise Beans: Session Beans & Entity BeansSession Beans & Entity Beans
Session Beans vs. Entity BeansSession Beans vs. Entity Beans
Bean-Managed PersistenceBean-Managed Persistence
Container-Managed PersistenceContainer-Managed Persistence
EJB Transaction AttributesEJB Transaction Attributes
Comparing Session and Comparing Session and Entity BeansEntity Beans
Mandatory for EJB 1.0Mandatory for EJB 1.0 Represents a specific Represents a specific
clientclient(1 instance per client)(1 instance per client)
Short-livedShort-lived TransientTransient Can be any Java classCan be any Java class May be transactionalMay be transactional Business Logic BeansBusiness Logic Beans
Optional for EJB 1.0Optional for EJB 1.0 Represents underlying Represents underlying
data object or contextdata object or context
(clients share instance)(clients share instance) Long-livedLong-lived PersistentPersistent Can be a class that maps Can be a class that maps
to persistent data to persistent data (e.g., database)(e.g., database)
Always transactionalAlways transactional Beans which represent Beans which represent
datadata
Session BeansSession Beans Entity BeansEntity Beans
Session BeansSession BeansRepresents Represents ProcessProcess
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 beansSession beans are often a client of multiple entity beans ImplementsImplements javax.ejb.SessionBeanjavax.ejb.SessionBean interfaceinterface State management types for session EJBsState management types for session EJBs
– stateful - session bean may maintain state information across stateful - session bean may maintain state information across method callsmethod calls
– stateless - session bean may be used to service multiple clientsstateless - 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 interfacecreate() method in its Home interface
Session Beans - Stateful or Session Beans - Stateful or StatelessStateless
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 Client. It maintains a user “session”. Most common example is an e-commerce application with a “shopping cart” unique for each user.e-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 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 container calls the ejbPassivate() method to save any private data to some physical storage.storage.
– When container receives new request, the Container will call the ejbActivate() method When container receives new request, the Container will call the ejbActivate() method to restore the Session Bean.to restore the Session Bean.
A Stateless Session Bean can be accessed by multiple incoming A Stateless Session Bean can be accessed by multiple incoming clients and keeps no private data. It does not maintain a unique clients and keeps no private data. It does not maintain a unique session with a client.session with a client.– Keeps no persistent data. If it crashes, container simply starts another one and the Keeps no persistent data. If it crashes, container simply starts another one and the
client transparently connects.client transparently connects.– All access to the Bean is serialized.All access to the Bean is serialized.
Entity BeanEntity Bean
Represents Represents DataData Implements Implements javax.ejb.EntityBean javax.ejb.EntityBean interfaceinterface Maps a data source to a Java classMaps a data source to a Java class
– table, view, join or stored procedure in a relational databasetable, view, join or stored procedure in a relational database– a set of related records in a databasea set of related records in a database– legacy datalegacy data
Each instance of an entity bean is one row of dataEach instance of an entity bean is one row of data Each instance of an entity bean is uniquely identified Each instance of an entity bean is uniquely identified
by a primary keyby 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 BeanDefining an Entity Bean An Entity Bean must implement the An Entity Bean must implement the
javax.ejb.EntityBean interface. In addition, the Entity javax.ejb.EntityBean interface. In addition, the Entity Bean must implement an ejbCreate() method for each Bean must implement an ejbCreate() method for each create() method on the Home Interface. create() method on the Home Interface.
When the Home class gets a call to create(), it calls When the Home class gets a call to create(), it calls the ejbCreate() method on the Entity Bean with the the ejbCreate() method on the Entity Bean with the corresponding signature.corresponding signature.
ejbStore() and ejbLoad() used to synchronize Entity ejbStore() and ejbLoad() used to synchronize Entity Bean data with the database.Bean data with the database.
ejbActivate() and ejbPassivate() used for notification ejbActivate() and ejbPassivate() used for notification that Entity Bean state is being written to the database that Entity Bean state is being written to the database or restored from the database.or 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 objectobject
Primary key can be saved and used Primary key can be saved and used later to regain access to the same later to regain access to the same EJB object identityEJB object identity– fooKey = fooBean.getPrimaryKey();fooKey = fooBean.getPrimaryKey();……fooBean = fooHome.findByPrimaryKey(fooKey);fooBean = fooHome.findByPrimaryKey(fooKey);
Entity Bean OperationsEntity Bean Operations BeanBeanHome.create() is equivalent to an SQL Home.create() is equivalent to an SQL
INSERTINSERT– Causes a new database record to be inserted Causes a new database record to be inserted
into the database:into the database: customerBean = customerHome.create(”Jane", customerBean = customerHome.create(”Jane", ”Rodgers");”Rodgers");
BeanBeanHome.findHome.findSomethingSomething() is equivalent to an () is equivalent to an SQL SELECTSQL SELECT– Creates a bean instance that represents queried data Creates a bean instance that represents queried data
from a databasefrom a database– Can also return an enumeration to represent multiple Can also return an enumeration to represent multiple
rows of datarows of data There will typically be many findThere will typically be many findSomethingSomething() methods:() methods:
customerBean = customerBean = customerHome.findByName(firstName, lastName); customerHome.findByName(firstName, lastName);
customerBeans = customerHome.findByZip(94023);customerBeans = customerHome.findByZip(94023);
Entity Bean OperationsEntity Bean Operations
BeanBeanHome.remove() and EJBObject.remove() Home.remove() and EJBObject.remove() are equivalent to an SQL DELETEare equivalent to an SQL DELETE– causes the database record to be deleted from causes the database record to be deleted from
the databasethe 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 UPDATEequivalent to an SQL UPDATE
customerBean = customerHome.findByName(“Jane”, customerBean = customerHome.findByName(“Jane”, “Rodgers”);“Rodgers”);customerBean.setEmailAddress(“[email protected]”);customerBean.setEmailAddress(“[email protected]”);
EJB PersistenceEJB Persistence
Provides Entity Beans the ability to Provides Entity Beans the ability to store and retrieve their statestore and retrieve their state
Can be implemented by a beanCan be implemented by a bean– Bean Managed PersistenceBean Managed Persistence
Can be implemented by a Can be implemented by a containercontainer– Container Managed PersistenceContainer Managed Persistence
Bean Managed PersistenceBean Managed Persistence
The entity bean is responsible for its persistent The entity bean is responsible for its persistent behaviorbehavior
EJB developer must implement database accessEJB developer must implement database access– ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()ejbCreate(…), ejbLoad(), ejbStore(), ejbRemove()
Not automated, developer manually creates Not automated, developer manually creates mapping through JDBC callsmapping through JDBC calls
Not as reusableNot as reusable– Hard-code database access within classHard-code database access within class
Advanced features like connection pooling and Advanced features like connection pooling and caching are difficult to support because of reliance caching are difficult to support because of reliance on hand written codeon hand written code
Container Managed Container Managed PersistencePersistence
The EJB container is responsible for The EJB container is responsible for persistencepersistence
The container provides tools that generate The container provides tools that generate code in the EJB class that maps methods in code in the EJB class that maps methods in the bean to a result setthe 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
databasedatabase– Server provides automated mapping to convert relational Server provides automated mapping to convert relational
data to bean instancesdata to bean instances
Advanced features like connection pooling Advanced features like connection pooling and caching are easily supportedand caching are easily supported
High reuseHigh reuse
EJB Transaction SupportEJB 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 DECLARETO DECLARE: EJB allows you to declare transaction support : EJB allows you to declare transaction support
in the Deployment Descriptor and then have the container in the Deployment Descriptor and then have the container take care of the details inside the remote classtake care of the details inside the remote class
Transaction attributes specified at the bean and method levelTransaction attributes specified at the bean and method level
– FOR EXPLICIT CONTROLFOR EXPLICIT CONTROL: An EJB Container is required to : An EJB Container is required to implement implement javax.transaction.UserTransactionjavax.transaction.UserTransaction
Provides an interface to a transaction serviceProvides 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 transactionsEJB specification does not support nested transactions
EJB Transaction AttributesEJB Transaction Attributes TX_NOT_SUPPORTEDTX_NOT_SUPPORTED
– Cannot execute within a transactionCannot execute within a transaction– Suspends any existing transaction while method is calledSuspends any existing transaction while method is called
TX_SUPPORTSTX_SUPPORTS– Executes with or without a transactionExecutes with or without a transaction– Doesn’t suspend existing transactionDoesn’t suspend existing transaction
TX_REQUIREDTX_REQUIRED– Executes within a transactionExecutes within a transaction– If no transaction exists, starts a new one and commits it when method If no transaction exists, starts a new one and commits it when method
completescompletes
TX_REQUIRES_NEWTX_REQUIRES_NEW– Always starts a new transaction and commits it when method completesAlways starts a new transaction and commits it when method completes– Suspends existing transactionSuspends existing transaction
TX_BEAN_MANAGEDTX_BEAN_MANAGED– The bean manages its own transaction controlThe bean manages its own transaction control– Suspends existing transactionSuspends existing transaction
TX_MANDATORYTX_MANDATORY– Must execute within a transactionMust execute within a transaction– If no transaction exists, throws the TransactionRequiredExceptionIf no transaction exists, throws the TransactionRequiredException