enterprise javabeans - wmich.edualfuqaha/cs595/lectures/lecture23.pdf · ejb as client/server...
TRANSCRIPT
Enterprise JavaBeans
What are EJBs?
They are components that can be connected to form a system
They can represent dataThey can represent behavior
Usually, EJBs fall into only one of these categoriesThey are typically used in the server tierEJBs can be persistedEJBs can interact with other EJBs
Advantages of EJBsEJBs are reusable components
Can be reused in different parts of the systemCan be packaged into libraries and sold
EJBs Can be combined visually using development IDEsE.g. Visual Age, Visual Café
EJBs provide convenient abstractions so it do not requireyou to write:
Multi-threaded, multiple access codeDatabase access code (e.g. JDBC)Network communication code (i.e. it uses RMI) for client/server communicationNetwork communication code for EJB to EJB communicationTransaction management code
EJBs from different businesses can interact easilyThis is because of their well-defined interfaces
EJB Communication
EJBs use IIOP as the wire protocolTherefore, EJBs are compatible with RMI (i.e., RMI over IIOP) and CORBA librariesThus, you could write an EJB client in any language that supports CORBA
EJB as Client/Server Middleware
Think of EJBs as just another Client/Server middleware like RMI, CORBA, or Web Services
The EJB instance itself is the serverEJBs have clients (objects that call its methods)
One complication is that EJB clients can be:Java Applets and Applications (using RMI or CORBA)Non-Java applications (using CORBA)JSPs and Servlets (using RMI or CORBA)Other EJBs (using RMI or CORBA)
EJBs & 3-Tiered ArchitecturesIn enterprise systems, EJB clients are usually: Servlets, JSPs, or Other EJBs
Applet
Web Page Servlets & JSPs
EJBs
Database
Client Tier Server Tier Database Tier
EJBs & Multi-Tiered Architectures
Applet
Web Page Servlets & JSPs
EJBs
Database
3rd PartyEJBs
How EJBs Change Things
EJBs are most suitable for developing business logic and data manipulation
If all of the business logic operations and data manipulations are done using EJBs, the JSPs and Servlets will be focused mainly on displaying the results of those operations
Session EJBs: Used to represent system behavior (i.e. business logic)
e.g. Storing products to purchase in the shopping cartEntity EJBs: Used to represent & manipulate system data
e.g. Finding products that match a search term
Application Servers
Containers where EJBs (and JSPs and servlets) are executedProvide EJB functionality, including:
Persistence through databases (using JDBC)Transactions (using Java Transaction Service)
Can provide advanced features, including:Load balancingDatabase connection pooling
Here are the major application servers:WebLogic (BEA), Internet Application Server or iAS(Oracle), WebSphere (IBM)
Alternatives to EJBs
Web Services are one of the technologies competing with EJBs
Web services use the SOAP protocol to exchange information with some server
SOAP uses an XML format to exchange request and response information via HTTPDue to SOAP's well-defined protocol, Web Services can be used to exchange information between businesses (B2B)
Web services provide one or more remote method that can be accessed easily from other applications
Alternatives to EJBsCORBA objects provide some functionality similar to EJBs:
Persistence (of CORBA object data)Transactions (between CORBA objects)Security (between CORBA objects)
CORBA and EJBs are closely related, in fact, they use the same wire protocol:
IIOPIn some sense, EJBs can be considered to be an enhanced version of CORBA
Except that EJBs can only be created in Java
Types of Enterprise Beans
Session beans:Also called business process objectsThey represent the business logic of the systemTheir lifetime is usually an entire session
When a session is done, the session bean expiresi.e. Session bean instances exist as long as a specific user is using the system
Entity beans:Also called business data objectsThey represent persistent data
Often the data persistence is managed through a database, using JDBC
Subtypes of Session Beans
Stateful:Used for operations that require multiple requests to be completedMaintain data between requests
Stateless:Used for operations that can be performed in a single requestDo not maintain persistent data between subsequent requests from a given client
Entity Beans Explained
Entity beans represent data in the systemIn addition, entity beans are used to search for, modify, create and delete dataUsually, this data resides in a relational databaseEach entity bean typically represents a single row in some database table
An entity bean instance exists as long as the data is being used
When the EJB client is done with the instance, the entity bean instance usually returns to a bean pool
The client for an entity bean is typically a session bean, sincebehavior usually involves the manipulation of data
Subtypes of Entity Beans
Bean-managed persistence:The entity bean handles its own persistence
Often via JDBC (or SQL/J) to a databaseThe bean author is required to write persistence-management code into the bean code itself
Container-managed persistence:The entity bean’s persistence is automatically maintained by the EJB containerThis is the easiest way, and often EJB containers do a better job because they provide extra features like connection pooling, load balancing, etc.This method is known to be extremely reliable, since CMP code is usually well tested
An EJB Autopsy
The remote interfaceDescribes the interface provided to EJB clients
The enterprise bean classThe implementation of the bean
The home interfaceDescribe how client can create, find, and remove EJB instances
The Remote InterfaceDescribes the interface provided to EJB clientsMust extends javax.ejb.EJBObjectThis interface usually provides a number of accessor methods (getters and setters) for the bean’s fields, as well as all business methods
The Enterprise Bean Class
The implementation of the beanThis is where the methods exported in the remote interface are definedBusiness logic and data operations occur hereEJB classes must implement one of the following interfaces: javax.ejb.SessionBean, javax.ejb.EntityBean
The Home Interface
The home interface describes any methods not requiring access to a particular bean instance
Methods for creating, finding, and deleting bean instances
Must extend javax.ejb.EJBHome
EJB Naming Conventions
Enterprise bean class:<name>Bean, e.g. CustomerBean
Home interface:<name>Home, e.g. CustomerHome
Remote interface:<name>, e.g. Customer
EJB Client Operation
An EJB client uses an EJB by first locating its home object
The methods on this home object are declared in the home interfaceThe home object is located using JNDI
The client tells JNDI what name the EJB goes by, and JNDI gives a home interface for that EJB
Once a home object is obtained, the client calls some home methods to access the EJB
e.g. The client may call “create” to create a new instance, “remove” to delete an instance, “findXYZ” to search for EJBs.
Example:Stateless Session Bean
The Remote Interface
import javax.ejb.*;import java.rmi.RemoteException;import java.rmi.Remote;
public interface Hello extends EJBObject {public String hello() throws
java.rmi.RemoteException;}
The Bean Class
public class HelloBean implements SessionBean {// these are required session bean methodspublic void ejbCreate() {}public void ejbRemove() {}public void ejbActivate() {}public void ejbPassivate() {}public void setSessionContext(SessionContext ctx) {}
// this is our business method to be called by the clientpublic String hello() {
return “Hello, world!”;}
}
Session Bean Required Methods
The following methods are defined in the SessionBeaninterface:void setSessionContext(SessionContext sc)
Stores the session context (used for communicating with the EJB container)
void ejbCreate(…init params…)Performs necessary initializations when an instance is created
void ejbPassivate()Releases any resources (database connections, files) before an instance is put into hibernation
void ejbActivate()Prepare needed resources to return from hibernation
void ejbRemove()Prepare for the bean’s destruction
The Home Interface
import javax.ejb.*;import java.rmi.RemoteException;
public interface HelloHome extends EJBHome {Hello create() throws RemoteException, CreateException;
}
The EJB Client
public class HelloClient {public static void main(String[] args) {
try {InitialContext ic = new InitialContext();Object objRef = ic.lookup("java:comp/env/ejb/Hello");HelloHome home =
(HelloHome)PortableRemoteObject.narrow(objRef, HelloHome.class);
Hello hello = home.create();System.out.println( hello.hello() );hello.remove();
} catch (Exception e) {e.printStackTrace();
}}
}
Example:Stateful Session Bean
The Remote Interface
import javax.ejb.*;import java.rmi.RemoteException;import java.rmi.Remote;
public interface Count extends EJBObject {public int count() throws
java.rmi.RemoteException;}
The Bean Class
public class CountBean implements SessionBean {private int val = 0;
public void ejbCreate() {}public void ejbRemove() {}public void ejbActivate() {}public void ejbPassivate() {}public void setSessionContext(SessionContext ctx) {}
// this is our business method to be called by the clientpublic int count() {
return ++val;}
}
The Home Interface
import javax.ejb.*;import java.rmi.RemoteException;
public interface CountHome extends EJBHome {Count create() throws RemoteException, CreateException;
}
The EJB Client
public class CountClient {public static void main(String[] args) {
try {InitialContext ic = new InitialContext();Object objRef = ic.lookup("java:comp/env/ejb/Count");CountHome home = (CountHome)
PortableRemoteObject.narrow(objRef, CountHome.class);Count count = home.create();System.out.println(“Count:”+count.count() );System.out.println(“Count:”+count.count() );System.out.println(“Count:”+count.count() );count.remove();
} catch (Exception e) {}}
}
Entity Beans
What Are Entity Beans?
They represent data elementsUnlike session beans, entity beans last longer than a client session
Entity beans last as long as the data they represent lasts
In reality, entity beans are a data access wrapper (e.g. database encapsulation)
When entity bean’s data is modified, so is the representative data in the database (& vice versa)Whether this is done by the container, or explicitly by the programmer, depends on what kinds of Entity bean it is
Entity Bean Data Mappings
Entity Bean pkField SomeField … …1 … … …2 … … …3 … … …
Entity Bean
Entity Bean
Entity Bean
Entity Bean Facts
The persistent data represented by the entity bean is stored safely
Usually in a databaseEntity beans keep their data even after a crash
Multiple entity beans can represent the same data in the database
Used for handling multiple clients who want to access the same data
Entity beans can be re-usedEntity beans of a given type may be placed into a pool and reused for different clientsThe data the entity beans represent will change
Example:Entity BeansBean-Managed Persistence
The Remote Interface
import javax.ejb.*;import java.rmi.*;
public interface Account extends EJBObject {public void deposit(double amount) throws RemoteException;public void withdraw(double amount) throws RemoteException;public double getBalance() throws RemoteException;
}
The Home Interface
import javax.ejb.*;import java.rmi.RemoteException;import java.util.*;
public interface AccountHome extends EJBHome {public Account create(Integer accountID, String owner)
throws RemoteException, CreateException;public Account findByPrimaryKey(Integer accountID)
throws FinderException, RemoteException;}
The Bean Classimport javax.ejb.*;import java.rmi.*;import java.util.*;
public abstract class AccountBean implements EntityBean {
public abstract void setAccountID(Integer accountID);public abstract Integer getAccountID();public abstract void setBalance(double balance);public abstract bouble setBalance();public abstract void setOwnerName(String ownerName);public abstract String getOwnerName();
public Integer ejbCreate(int accountID, String owner) throws CreateException { setAccountID(accountID);setOwnerName(owner);return new Integer(0);}
public void ejbPostCreate(int accountID, String owner) {} public void ejbRemove() {} public void ejbActivate() {}public void ejbPassivate() {}public void ejbLoad() {} public void ejbStore() {} public void setEntityContext(EntityContext ctx) {}public void setEntityContext() {}
The Bean Class (contd.)
public void withdraw(double amount){
setBalance( getBalance() - amount ); }
public void deposit(double amount){
setBalance( getBalance() + amount ); }
}
EJB Packaging and Deployment
Step 1: Compile Java Classes (remote interface, home interface, and the bean class).Step 2: Package the EJB using the deployment tool.Step 3: Deploy the EJB using the deployment toolStep 4: Run the client to use the EJB
Create New Enterprise Bean
Create New Enterprise Bean (Contd.)
Create New Enterprise Bean (Contd.)
Add Remote, Home, and Bean Classes
Create New Enterprise Bean (Contd.)
General Settings
Entity Settings
Create New Enterprise Bean
Sun-Specific Settings
Sun-Specific Settings (Contd.)
Sun-Specific Settings (Contd.)
Save EJB JAR
Start J2EE Application Server
Start PointBase DBMS
Deploy EJB
The EJB Client
public class AccountClient {public static void main(String[] args) {
try {Context ctx = new InitialContext();Object ref = ctx.lookup(“java:comp/env/ejb/Account”);AccountHome home = (AccountHome)PortableRemoteObject.narrow(objRef, AccountHome.class);Account newAccount = home.create(123, “John Smith”);newAccount.deposit(100);newAccount.remove();Collection accounts = home.findByOwnerName(“John Smith”);
} catch (Exception e) {}}
}
ReferencesDeveloping Enterprise Applications Using the J2EE Platform, http://java.sun.com/developer/onlineTraining/J2EE/Intro2/j2ee.html