Enterprise java beans(ejb) update 2

72
Enterprise Java Beans(EJB) With EJBs, you can develop building blocks ‘ejb components ’ – that u and someone else can assemble and reassemble into different applications. For example , you might create a customer bean that represents a customer in database. You can use that Customer bean in an accouting program, an e-commerce shopping cart and a tech support application. One beauty of EJBs is that you take code reuse to a whole new level, instead of just code it reuses whole functionality and allows you modify that way bean behaves at runtime with touching its java code. 05/10/22 1 JavaTruths.com:A Portal for all java related stuff!!!

Transcript of Enterprise java beans(ejb) update 2

Page 1: Enterprise java beans(ejb) update 2

Enterprise Java Beans(EJB)With EJBs, you can develop building blocks ‘ejb components ’ – that u and someone else can assemble and reassemble into different applications.For example , you might create a customer bean that represents a customer in database. You can use that Customer bean in an accouting program, an e-commerce shopping cart and a tech support application.One beauty of EJBs is that you take code reuse to a whole new level, instead of just code it reuses whole functionality and allows you modify that way bean behaves at runtime with touching its java code.

04/12/23 1JavaTruths.com:A Portal for all java related stuff!!!

Page 2: Enterprise java beans(ejb) update 2

Enterprise Java Beans: What really EJBs gives you

• EJB lets you focus on the business logic for your business, and leave the underlying services (transaction,networking, security etc.) to the EJB server vender.

• EJB let’s you customize and configure reusable components at deploy time with out touching the source code.

• EJBs are portable not just to different JVM’s but to different EJB servers.

04/12/23 2JavaTruths.com:A Portal for all java related stuff!!!

Page 3: Enterprise java beans(ejb) update 2

How does it all works?

Beans run under the control of ejb server.The server steps into the middle of every method

call from a client to a bean and inserts the “services ” like security, transactions and persistence.

04/12/23 3JavaTruths.com:A Portal for all java related stuff!!!

Page 4: Enterprise java beans(ejb) update 2

Type of Beans

• Entity Bean - Use an entity bean to represent thing in persistent store. That almost always means something in a database, where an instance of an entity bean represents a row in a table.

• Message driven bean- use a message driven bean only when you need a JMS Consumer. In other words, a bean that can listen for message from a JMS messaging service.

• Session – use a session bean for … everything else. Where an entity bean represents a thing, a session bean typically represents a process.

04/12/23 4JavaTruths.com:A Portal for all java related stuff!!!

Page 5: Enterprise java beans(ejb) update 2

Session Bean can be stateless or stateful

• Session bean can be marked (at deployment time) as either stateless or stateful.

• A stateful bean can remember conversational state between method calls, while stateless bean won’t remember anything about the client between method invocations.

• Stateful session beans are less-scalable.

04/12/23 5JavaTruths.com:A Portal for all java related stuff!!!

Page 6: Enterprise java beans(ejb) update 2

FIVE THING YOU DO TO BUILD A BEAN

I. Code the bean class with all of the business methods,

II. Code two interfaces for the bean: home and component.

III. Create an XML deployment descriptor that tells the server what your bean is and how it should be managed. You must name it as ejb-jar.xml

IV. Put the bean, the interfaces and the DD into an ejb-jar file.

V. Deploy the bean into the server, using the tools provided by the server vendor.

04/12/23 6JavaTruths.com:A Portal for all java related stuff!!!

Page 7: Enterprise java beans(ejb) update 2

Write the Bean Class

• Bean class provides the implementation of the business methods declared in the component inteface.

• There are three types of beans, Session, Entity and Message – Driven.

• Before making a bean, you must decide what type you need becoz your bean class must implement one of three interfaces, depending on the type you choose.

04/12/23 7JavaTruths.com:A Portal for all java related stuff!!!

Page 8: Enterprise java beans(ejb) update 2

AdviceGuy Bean

• Advice Guy gives back an advice string when you invoke the getAdvice() method.

• We’ve chosen a Session bean here becoz its perfect for AdviceGuy application.

• So, our bean class implements the SessionBean interface and SessionBean has methods your bean class must implement.

• The methods you implement from SessionBean interface are known as container callbacks, becoz the container uses then to notify you of important milestone in the bean’s life cycle.

04/12/23 8JavaTruths.com:A Portal for all java related stuff!!!

Page 9: Enterprise java beans(ejb) update 2

BEAN CLASSimport javax.ejb.*;public class AdviceBean implements SessionBean{

private String[] adstring=“advice string goes here”;public void ejbActivate(){}public void ejbPassivate(){}public void ejbRemove(){}public void setSessionContext(SesssionContext sc){

}

public String getAdvice(){return adstring;

}public void ejbCreate(){}

}

You need this package

These four methos are from SessionBean interface, so you have to put them here,for now worry about what these are for!

You must have an ejbCreate() method. Its an ejb rule we’ll learn about later. But it doesn’t come

from SessionBean interface.

You must implemet one of three bean type interfaces:

04/12/23 9JavaTruths.com:A Portal for all java related stuff!!!

Page 10: Enterprise java beans(ejb) update 2

Write two interfaces for the Bean

These are the two interfaces that client sees;COMPONENT interface:This is whre all the business methods are declared.

In other words,it’s where yo put all the methods the client wants to call.

import javax.ejb.*;import java.rmi.RemoteException;public interface Advice extends EJBObject{

public String getAdvice() throws RemoteException;

}

It must extend either the EJBObject or EJBLocalObject.

This is the actual business method. It MUST correspond to a method

in the bean class.04/12/23 10JavaTruths.com:A Portal for all

java related stuff!!!

Page 11: Enterprise java beans(ejb) update 2

Write two interfaces for the Bean

These are the two interfaces that client sees;COMPONENT interface:This is whre all the business methods are declared.

In other words,it’s where yo put all the methods the client wants to call.

import javax.ejb.*;import java.rmi.RemoteException;public interface Advice extends EJBObject{

public String getAdvice() throws RemoteException;

}

It must extend either the EJBObject or EJBLocalObject.

This is the actual business method. It MUST correspond to a method

in the bean class.04/12/23 11JavaTruths.com:A Portal for all

java related stuff!!!

Page 12: Enterprise java beans(ejb) update 2

Home Interface

• The client uses the home interface to ask for a reference to the component interface. The home is the client’s starting point for getting hold of a reference to a bean.

import javax.ejb.*;import java.rmi.RemoteException;public interface AdviceHome extends EJBHome{

public Advice create() throws CreateException,RemoteException;

}

The create() method must return your component interface type!!

The home must extend either the EJBHome interface or EJBLocalHome

04/12/23 12JavaTruths.com:A Portal for all java related stuff!!!

Page 13: Enterprise java beans(ejb) update 2

Create an XML DD <?xml version="1.0"?> <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'> <ejb-jar> <enterprise-beans> <session>

<ejb-name>AdviceBean</ejb-name> <home>AdviceHome</home> <remote>Advice</remote> <ejb-class>AdviceBean</ejb-class> <session-type>Stateless</session-type><transaction-type>Bean</transaction-type><security-identity>

<description></description><use-caller-identity></use-caller-identity>

</security-identity></session></enterprise-bean></ejb-jar>

Specify home interface name

Remote interface

04/12/23 13JavaTruths.com:A Portal for all java related stuff!!!

Page 14: Enterprise java beans(ejb) update 2

Put the Bean, the interface and the DD into ejb-jar file

META-INF

EJB-JAR.XML

MYPACKAGE

AdvcieBean.class

AdviceHome.class

Advice.class

MYEJB.JAR

ejb-jar.xml must be in a directory named

META-INF

04/12/23 14JavaTruths.com:A Portal for all java related stuff!!!

Page 15: Enterprise java beans(ejb) update 2

Deploy the bean into the server,using the tools provided by the server

vendor

04/12/23 15JavaTruths.com:A Portal for all java related stuff!!!

Page 16: Enterprise java beans(ejb) update 2

How to call a bean from Client Side?

I. Get a reference to a JNDI InitialContext II. Use the InitialContext to do a lookup on the

home interface of the Bean(that we named “Advisor” when we deployed)

III. Narrow and Cast the thing we get back from the lookup.(that thing is something that implements the AdviceHome interface).

IV. Call Create on the home interface to get back a reference to the component interface.

V. Call getAdvice()(“the business method”) on the component interface and print the result.

04/12/23 16JavaTruths.com:A Portal for all java related stuff!!!

Page 17: Enterprise java beans(ejb) update 2

The Client Code(AdviceClient.java)

import javax.naming.*;Import java.rmi.*;Import javax.rmi.*;Import javax.ejb.*;Public class AdviceClient{

public static void main(String[ ] args){new AdviceClient().go();

}public void go(){

try{Context ic=new InitialContext();Object o=ic.lookup(“Advisor”);AdviceHome

home=(AdviceHome)PortableRemoteObject.narrow(o,AdviceHome.class);Advice advisor=home.create();System.out.println(advisor.getAdvice());

}catch(Exception ex){ ex.printStackTrace();}}

} Finally we get to the actual business methods.

Lookup the AdviseBean using the JNDI name we gave during

deployment.

Initialcontext is our entrypoint into JNDI

directory

04/12/23 17JavaTruths.com:A Portal for all java related stuff!!!

Page 18: Enterprise java beans(ejb) update 2

EJB ARCHITECTURE

04/12/23 18JavaTruths.com:A Portal for all java related stuff!!!

Page 19: Enterprise java beans(ejb) update 2

EJB uses RMI

04/12/23 19JavaTruths.com:A Portal for all java related stuff!!!

Page 20: Enterprise java beans(ejb) update 2

How EJB uses RMI

04/12/23 20JavaTruths.com:A Portal for all java related stuff!!!

Page 21: Enterprise java beans(ejb) update 2

EJB uses RMI

• In EJB, the Remote object(EJB Object) is the bean’s bodyguard. The Bean sits back, protected from all client invocations, while EJBObject implements the Remote interface and takes the remote calls.

• Once the call gets to the EJBObject, the server jumps in with all the services.

• The EJBObject implemens the Remote business interface, so the remote calls from the client come to the EJBObject. But it’s still the bean that has the business logic, even though the bean doesn’t implement the Remote interface.

04/12/23 21JavaTruths.com:A Portal for all java related stuff!!!

Page 22: Enterprise java beans(ejb) update 2

***

• Both the Remote object and the stub implement the same interface – the business interface(called a component interface) – but without the real business behavior.

• The Bean class does NOT implement the business interface but the bean has the real business logic functionality.

04/12/23 22JavaTruths.com:A Portal for all java related stuff!!!

Page 23: Enterprise java beans(ejb) update 2

***

• In EJB, the business interface is called the component interface. This is where you expose your business to the client.

• A Bean may have multiple business interfaces according to the client’s need.

• A component inteface extends EJBObject interface that extends java.rmi.Remote interface.

04/12/23 23JavaTruths.com:A Portal for all java related stuff!!!

Page 24: Enterprise java beans(ejb) update 2

Tricky Questions

Who writes the class that really DOES implement the component interface? In other words, who makes the EJBObject Class?

The Container creates four things:I. The EJBObject class(implements your component

interface)II. The EJBObject stub class (implements component

interface and knows how to talk to the EJBObject)III.The Home class (implements the home interface)IV.The Home stub class(implements your home

interface and knows how to talk to the home)

04/12/23 24JavaTruths.com:A Portal for all java related stuff!!!

Page 25: Enterprise java beans(ejb) update 2

How EJB really Works?

04/12/23 25JavaTruths.com:A Portal for all java related stuff!!!

Page 26: Enterprise java beans(ejb) update 2

How EJB really Works?

04/12/23 26JavaTruths.com:A Portal for all java related stuff!!!

Page 27: Enterprise java beans(ejb) update 2

How EJB really Works?

04/12/23 27JavaTruths.com:A Portal for all java related stuff!!!

Page 28: Enterprise java beans(ejb) update 2

The Bean Home

• Every Session and Entity Bean has a Home.• Message Driven Beans don’t have homes because

message-driven beans don’t have a client view.• The Home object has one main job: to hand out

references to a bean’s component interface. • Each deployed bean has its own Home object (only

one ), and that Home is responsible for all bean instances of that type. If you deploy three beans as part of an application there will be three Homes in the server representing each of those three beans. It makes no differences how many EJBObjects and stubs the Home object hand out, there will still be only three Homes.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

28

Page 29: Enterprise java beans(ejb) update 2

Architectural Overview: Session Beans

• Client Share the home but never the bean.• Each client gets his own EJBObject reference and

his own bean. The client never shares a bean with another bean, the meaning of “shares” depends on whether the bean is stateful or stateless.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

29

Page 30: Enterprise java beans(ejb) update 2

Architectural Overview: Entity Bean

• Clients share the Home and may share the bean.• If two clients are trying to access the same

customer, then both clients have a reference to the same EJBObject. If a client wants to access two different customers, though, the client will have two stubs, and those stubs will be for two different EJBObjects, one for each customer.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

30

Page 31: Enterprise java beans(ejb) update 2

Architectural Overview: Session Beans

Creating a stateful Session BeanThe home creates the bean and the EJBObject for the

bean and hands back the EJBObject stub.Creating a stateless Session BeanThe Home gives the client a stub to an existing EJBObject

but does not associate a bean with this EJBObject instead, the bean stays in a pool until the client uses the EJBObject stub to call a business method.

Stateless session beans aren’t created until the container decides it needs on and that’s really up to the container.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

31

Page 32: Enterprise java beans(ejb) update 2

Stateless session beans are more scalable

• Clients don’t share EJBObjects but the same bean can service multiple EJBObjects. Just not at the same time. A single bean can handle multiple clients, as long as only one client at a time is in the middle of a business method invocations.

• The stateful bean holds client conversational state. That means the bean has to save client specific state across multiple method invocations from the client.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

32

Page 33: Enterprise java beans(ejb) update 2

Tricky Questions

How long does a stateful bean keep client specific state:• A session continues until the client tells the bean he’s

done(by calling remove() on the bean’s component interface) or the server crashes or the bean times out.

How can a stateful session bean be scalable if you always need one bean for every client?

• You do need a separate bean allocated for each client, but not every bean has to be actively consuming resources. If a stateful session bean client is taking a long time between method calls, a stateful session bean can be temporarily taken down and put in state called passivation.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

33

Page 34: Enterprise java beans(ejb) update 2

JNDI

• JNDI stands for Java Naming and directory interface and its an API for accessing naming and directory services.

• The JNDI API can work with many different services as long as that service has a JNDI driver (called service provider) . It’s a lot like JDBC.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

34

Page 35: Enterprise java beans(ejb) update 2

• Getting a home interface stub• Get a InitialContextContext ic=new InitialContext();The InitialContext is your entry point into JNDI

tree.it’s simly the first context from which you start navigating. Kind of like your current working directory.

• Lookup the bean’s home using the initialContextObject o=ic.lookup(“Advisor”);

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

35

Page 36: Enterprise java beans(ejb) update 2

• Assign the result of the lookup to the Home interface reference

AdviceHome home=(AdviceHome)o;The home stub returned from a JNDI lookup might

not implement the home interface!You might get an IIOP stub that isn’t castable to the

home interface of your bean.To get a stub that’s castable to the home interface,

you have to first narrow() the object.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

36

Page 37: Enterprise java beans(ejb) update 2

• Narrowing an objectAdviceHome home=(AdviceHome)

PortableRemoteObject.narrow(o, AdviceHome.class);

Call Create on the home interface to get the EJB object stub.

Advice advisor=home.create();Call the business method on the component

interface.

System.out.println(advisor.getAdvice());04/12/23 JavaTruths.com:A Portal for all

java related stuff!!!37

Page 38: Enterprise java beans(ejb) update 2

Rules for the home interface

Writing the remote home interface for the session bean• For a stateless session bean there can be only one

create() and it must NOT have arguments.• Stateful session beans can have multiple overloaded

create() methods and don NOT need to have no-arg create()

• All create() methods must declare a CreateException and RemoteException.

• The name of create methods in stateful beans must begin with “create”.(createAccout() .. etc)

• For stateful session beans arguments must be serializable.

04/12/23 JavaTruths.com:A Portal for all

java related stuff!!!38

Page 39: Enterprise java beans(ejb) update 2

Get reflection like information about the bean.

You can use to get more specific class information

about the bean.

EJBHome interface

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

39

• It has four methodsEJBMetaData getEJBMetaData()HomeHandle getHomeHandle()void remove(Handle h)void remove(Object key)

Serialize the home so that you can get the home again later, without having to go through

JNDI.

Page 40: Enterprise java beans(ejb) update 2

EJBHome interface

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

40

• It has four methodsEJBMetaData getEJBMetaData()HomeHandle getHomeHandle()void remove(Handle h)void remove(Object key)

When u are done with session bean,you can

tell the home by calling remove() and passing

the EJB object’s handle.

Tell the home to remove an entity bean.

You can’t call remove(Object primarykey) method on session bean it will throw RemoveException.

Page 41: Enterprise java beans(ejb) update 2

Rules for the component interface

• Extend EJBObject• Declare one or more business methods that throw

a RemoteException.The container implements the component interface

and matching stub. the container implements all the methods declared

in EJBObject.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

41

Page 42: Enterprise java beans(ejb) update 2

EJBObject methods

• getPrimaryKey()• getEJBHome()• getHandle()• remove()• isIdentical()

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

42

Get the primary key of an entity beanThis doesn’t apply to session bean and

throws RemoteException.

Page 43: Enterprise java beans(ejb) update 2

EJBObject methods

• getPrimaryKey()• getEJBHome()• getHandle()• remove()• isIdentical(object o)

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

43

Get the bean’s home object.

Save a reference to the EJBObject so that you can get back to your

original EJB object.

Tell the bean you are done with it. Container removes the resources

held by the session bean.

Compare the EJB object references to see if they reference the same bean.

Page 44: Enterprise java beans(ejb) update 2

The Handle

• The handle is a serializable thing that knows how to get back to the stub. It has a single method:

EJBObject getEJBObject() So when you call it you have to cast and narrow the

stub that comes back!

Just becoz you still have a handle, doesn’t mean the server still has your bean.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

44

Page 45: Enterprise java beans(ejb) update 2

isIdentical?

Stateless session beans: returns true if both references came from the same home.

Stateful session beans: false, no matter what, for any two unique stubs, even if from the same home.

Entity Beans: returns true if the two stubs refer to two entities with the same primary key.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

45

Page 46: Enterprise java beans(ejb) update 2

Session Bean life cycle

Stateful Session Beans• Creation• Use • Passivation • Activation• removalStateless Session Beans• Creation• Use• removal

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

46

Page 47: Enterprise java beans(ejb) update 2

Container Callbacks

• Life cycle event of beans are notified by container by calling callback methods

• Session has four callback methods ejbActivate() ejbPassivate() ejbRemove() setSessionContext(SessionContext ctx) ejbCreate()

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

47

Page 48: Enterprise java beans(ejb) update 2

ejbCreate method?

• Every session bean must have at least one ejbCreate() method to match create() method declared in the home interface.

• For stateless session there is only one no-arg create() method.

• For stateful session bean there can be mutiple n overloaded create methods.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

48

Page 49: Enterprise java beans(ejb) update 2

Container callbacks invocation

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

49

Does not Exist

Method ready

Passivated

setSessionContext()

ejbCreate()

ejbPassivate()

ejbActivate()

ejbRemove() or timeout

Bean throw system exception

timeout

Page 50: Enterprise java beans(ejb) update 2

Bean’s Context

A bean’s context is the bean’s only access to the containers. It lets you

• Get a reference to the home• Get a reference to EJB object• Get security information about the client• For a transaction to rollback• Find out if the transaction has already been set to

rollback• Get a transaction and call method on it.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

50

getEJBHome()getEJBLocalHome()

getEJBObject()getEJBLocalObject()

getCallerPrincipal()isCallerInRole(String

s)

setRollbackOnly(bollean b )getRollbackOnly()

getUserTransaction()

Page 51: Enterprise java beans(ejb) update 2

How to use setSessionContext(Sessioncontext sc)

• setSessionContext method is overridden to save a reference to the sessioncontext object created by container.private SessionContext context;public void setSessionContext(SessionContext sc){

context=sc;}

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

51

Page 52: Enterprise java beans(ejb) update 2

How to use ejbCreate()?

• for stateful session beans, the create method has arguments and container pass those arguments to matching ejbCreate method, you can use these argument to INITIALIZE your session bean state.

private String name;

public void ejbCreate(String clientName){Name=clientName;

• }

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

52

Page 53: Enterprise java beans(ejb) update 2

Use sessioncontext for

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

53

setSessionContext() ejbCreate() Within business method

Use your SessionContext for:

Get a reference to your home Get a reference to home Get a reference to home

Get a reference to your EJB Object

Get a reference to your EJB Object

Get security info about the client Get security info about the client

Get a transaction reference and call methods on it(BMT Beans)

For a transaction to rollback(CMT beans)

Find out if the transaction has already been set to rollback(CMT beans)

Get a transaction reference and call methods on it (BMT beans)

Access:

Your special JNDI Environment Your special JNDI Env. Your special JNDI Env.

Another beans methods Another beans methods

A resource manager(like a DB) A resource manager(like a DB)

Page 54: Enterprise java beans(ejb) update 2

Removing a stateful bean

• Client calls remove() on an active (non-passivated) bean.

• Bean times out while active.• Bean times out while passivated.• Bean throws a system exception.ejbRemove() method?Release any resources or do whatever clean up you

need to do before the bean dies forever.public void remove(){

try{myResource.close();

}catch(Exception e){…}}

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

54

Page 55: Enterprise java beans(ejb) update 2

Entity Beans

• Entity beans represent something from relational database in the form of object.

• Entity bean represent an entity.• Entities are persistent in underlying database.• If entity is removed from the database, entity

bean disintegrates, but if entity bean is dies, as an instance on the heap, it doesn’t kill the real entity in the database, until remove() is called.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

55

Page 56: Enterprise java beans(ejb) update 2

import javax.ejb.*;

import javax.sql.*;

import javax.naming.*;

public abstract class CustomerBean implements EntityBean {

private EntityContext context;

private String lastName;

private String firstName;

private String primaryKey;

public String ejbCreate(String last, String first) throws CreateException {

lastName=last;

firstName=first;

primaryKey=this.getPK();

return primaryKey;

}

public String getLastName() { return lastName; }

public void setLastName(String name) { lastName=name; }

public String getFirstName() { return firstName; }

public void setFirstName(String name) { firstName=name; }

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

56

The entity bean’s state includes the fields that map to columns in the customer database table.

Plain old java getters and setters for

persistent fields.the result of these setters will ultimately lead to

database update .

Page 57: Enterprise java beans(ejb) update 2

public void ejbActivate() { }

public void ejbPassivate() { }

public void ejbRemove() { }

public void setEntityContext(EntityContext ctx) {

context = ctx;

}

public void unsetEntityContext() { }

public void ejbLoad() { }

public void ejbStore() { }

public abstract String getPK(){

return ""+(int)(Math.random()*42);

}

}

}

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

57

Three container callbacks from EntityBean, that were also in SessionBean.but they have completely diff meaning here…

These are three new container callbacks from the EntityBean

interface.

Page 58: Enterprise java beans(ejb) update 2

Entity Bean Remote Component interface

import javax.ejb.*;import java.rmi.RemoteException;

public interface Customer extends EJBObject {

public String getLastName() throws RemoteException; public void setLastName(String lastName) throws RemoteException;

public String getFirstName() throws RemoteException; public void setFirstName(String firstName) throws RemoteException;}

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

58

Page 59: Enterprise java beans(ejb) update 2

Remote Component Interface

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

59

Page 60: Enterprise java beans(ejb) update 2

Entity Bean Remote Home Interface

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

60

Page 61: Enterprise java beans(ejb) update 2

Entity Bean Remote Home interfaceimport javax.ejb.*;import java.rmi.RemoteException;import java.util.Collection;

public interface CustomerHome extends EJBHome { public Customer create(String last, String first) throws CreateException,

RemoteException; public Customer findByPrimaryKey(String key) throws FinderException,

RemoteException; public Collection findByCity(String city) throws FinderException,

RemoteException;}• The create and finder methods in an entity bean home always give back

the bean’s component interface.• For create() and findByPrimaryKey(), the client gets a reference to one

EJBObject.• For multiple entity finders the client might get a collection

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

61

Page 62: Enterprise java beans(ejb) update 2

Entity bean create() and remove()

Client calls it to insert a new row in the database! It returns a reference to EJB object to the newly created entity.

The container does not make a new entity bean, but it does pull one out of the pool to run the ejbCreate() method.

Client calls remove() to delete the entity with this primary key and container calls ejbRemove().

Client gets an exception if he tries to use the ejb ref after removing the bean.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

62

Page 63: Enterprise java beans(ejb) update 2

Entity bean synchronization

The container’s main job for entity bean is to keep it synchronized with the underlying database entity.

I. Client calls a business method.II. Container intercepts the call and starts a

transaction before getting the beanIII.Container tells the database to lock the row.IV.Container loads the bean with the entity state

from the database. Now nobody can except the bean can change the entity bean.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

63

Page 64: Enterprise java beans(ejb) update 2

Entity bean synchronization

V. Beans runs mulitple business methods in the same transaction, knowing that the underlying entity data in the database can’t be changed.

VI. Container ends the transaction but the first it updates the database with whatever new state the bean might have been caching on behalf of that entity.

VII.Container tells the database to release lock on the entity row.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

64

Page 65: Enterprise java beans(ejb) update 2

Who does the work of synchronization?

YOU bean managed persistence (BMP)

Container Container managed persistence (CMP)

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

65

Page 66: Enterprise java beans(ejb) update 2

Container Managed Persistence

Added in ejb1.1; greately enhanced in EJB2.0The bean provider designs the entity bean class, choosing which of

the bean’s fields are part of the bean’s persistent state.Persistent fields map to columns in one or more database tables.

The container keeps track of changes to the bean’s state and updates the real entity as needed.

The bean provider writes the EJB QL to tell the container how to do selects. EJB QL is like a subset of SQL, but with some OO features.

Using info in the DD , the container writes the actual impl of the CMP Bean,including implementing the finder and select methods and all of the database access code.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

66

Page 67: Enterprise java beans(ejb) update 2

Bean managed Persistence

• Bean provider writes the database access code.• The container will at least tell a BMP bean when to go to the

database, so with BMP you don’t have to put in logic to keep the bean and the database in sync.

• The container invokes a container callback on the bean when the bean needs to do something with the database, and the bean code does the actual jdbc work.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

67

Page 68: Enterprise java beans(ejb) update 2

How actual bean is accessed?

I. Client call a business method for entity bean #28.II. The call is passed to EJBObject.III. The EJBObject get the call and but there may not be any entity

bean attached.IV. The container ‘activates’a bean by pulling it out of the pool and

calling ejbActivate().V. The container does a select on primary key #28 in the DB, to get

the real entity data to put into the bean.VI. The container loads the bean with the entity data from the DB,

and then calls ejbLoad() to tell the bean.

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

68

Page 69: Enterprise java beans(ejb) update 2

ejbPassivate()?

• Entity BeanCalled when the bean has finished a business method

and it is about to go back to the pool. Use it release resources.

• Stateful Session BeanCalled when the container decides to conserve

resources between business method invocations from the client.use it release resources and to prepare the bean’s state for what might be serialization.

• Stateless session beanDoesn’t Apply!!!04/12/23 JavaTruths.com:A Portal for all

java related stuff!!!69

Page 70: Enterprise java beans(ejb) update 2

CMP entity Bean is abstract?

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

70

Match every create with ejbCreate() and ejbPostCreate()

Match every home method with and ejbHome<Mname>

The finder methods are part of the bean class, but we won’t actually define them in our bean in case of CMP.

Page 71: Enterprise java beans(ejb) update 2

What to put in a bean class?

Things from home interface• For each create() method in the home, we’ve matching ejbCreate

and ejbPostCreate.• For each business method in the home, we’ve a matching

ejbHome<method>.• For CMP bean, we ll nt write matching finder methods.Things from the component interface• For each method in the component interface we must have a

concrete impl.Things from EntityBean interface• Implement all methodsVirtual persistent fields• For each persistent field, provide an abstract getter and setter.• Virtual fields are not instance variables!

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

71

Page 72: Enterprise java beans(ejb) update 2

04/12/23 JavaTruths.com:A Portal for all java related stuff!!!

72