ejbe slides
TRANSCRIPT
Copyright © 2000, BEA Systems Inc.EJBE-1Developing Enterprise Applications with BEA WebLogic Server
Module
EJBEEntity EJBs
At the end of this module you will be able to:• understand how entity EJBs stay persistent• write entity EJBs from scratch• connect an entity EJB to a data source
Copyright © 2000, BEA Systems Inc.EJBE-2Developing Enterprise Applications with BEA WebLogic Server
Section
1Entity EJB Basics
At the end of this section you will be able to:• design an entity EJB that is mapped to a datasource• describe the differences between CMP and BMP• write a container managed entity EJB
Copyright © 2000, BEA Systems Inc.EJBE-3Developing Enterprise Applications with BEA WebLogic Server
What is an Entity EJB?What is an Entity EJB?
§ Entity EJBs have the following behavior:Ø they are a representation of persistent dataØ they can survive a crashØmultiple clients can be using EJBs that
represent the same dataØ the EJB instance contains a “copy” of the data
in the persistent store
Copyright © 2000, BEA Systems Inc.EJBE-4Developing Enterprise Applications with BEA WebLogic Server
Persistence ManagementPersistence Management
§ The attributes of the object must be stored using a persistent mechanism.§ Examples of persistence management
include:Ø serialization to a fileØ relational database mappings through JDBC
Client-clientID-corporateName-address-town-postcode
Persistent Storage
database,files, etc...
Object in memory
Copyright © 2000, BEA Systems Inc.EJBE-5Developing Enterprise Applications with BEA WebLogic Server
Shared Entity EJBsShared Entity EJBs
§When multiple clients share an entity EJB they:Ø receive their own instanceØ share the underlying dataØ do not have to handle synchronization
Client
Client
Persistent StorageClient
Server
Entity EJB
Client Context
Container
Copyright © 2000, BEA Systems Inc.EJBE-6Developing Enterprise Applications with BEA WebLogic Server
Primary KeysPrimary Keys
§ Every entity EJB has a set of attributes that are unique when aggregated together.§ The aggregated attributes are called the
primary key of an entity EJB.
Copyright © 2000, BEA Systems Inc.EJBE-7Developing Enterprise Applications with BEA WebLogic Server
ObjectObject--Relational MappingRelational Mapping
§ An O-R mapping stores each object in a single row of a table.§ A database column is associated with each
attribute of the class. Client
••Client IdClient Id•Corporatename•Address•Town•Postcode
clientIdclientId Corporate Name Address Town Postcode
411MEB MEB 1, Lichfield Road B ’ham B7 4TU411PIT PITCH 34, London Road Chester C60 7YJ411WC World Company 1, The Strand London W1 8PL
Primarykey
Copyright © 2000, BEA Systems Inc.EJBE-8Developing Enterprise Applications with BEA WebLogic Server
Identical Identical Enitity Enitity EJBsEJBs
§ Two entity EJBs are identical if the contents of their primary keys are identical.
Client
Client
Persistent StorageClient
Server
Entity EJB
Client Context
Container
Primary Key
Copyright © 2000, BEA Systems Inc.EJBE-9Developing Enterprise Applications with BEA WebLogic Server
Types of PersistenceTypes of Persistence
§ There are two types of persistent EJBs:ØContainer-Managed Persistence (CMP)Ø Bean-Managed Persistence (BMP)
Client
Persistent Storage
Client
Server
Entity EJB
Client Context
Container
CMP
BMP
The Logic is here!
Copyright © 2000, BEA Systems Inc.EJBE-10Developing Enterprise Applications with BEA WebLogic Server
Entity vs. Session EJB AuthoringEntity vs. Session EJB Authoring
Differences Between Writing Entity EJBs and Session EJBs:1. You must write a primary key class.2. The home interface must have a findByPrimaryKey(<PrimaryKey>)
method.3. The home interface can have other find(…) methods.4. The bean class must implement the javax.ejb.EntityBean interface.5. The bean class must provide an ejbCreate(…) AND an
ejbPostCreate(…) for each create(…) listed in the home interface.
Differences Between Writing Entity EJBs and Session EJBs:1. You must write a primary key class.2. The home interface must have a findByPrimaryKey(<PrimaryKey>)
method.3. The home interface can have other find(…) methods.4. The bean class must implement the javax.ejb.EntityBean interface.5. The bean class must provide an ejbCreate(…) AND an
ejbPostCreate(…) for each create(…) listed in the home interface.
Copyright © 2000, BEA Systems Inc.EJBE-11Developing Enterprise Applications with BEA WebLogic Server
Primary Key ClassesPrimary Key Classes
§ A primary key object is the unique identifier of an EJB.§ A primary key class must:Ø be declared publicØ implement java.io.SerializableØ have a no-argument constructorØ have all of its attributes be declared public
Sample Primary Key Class:public class AlarmClockPK implements java.io.Serializable {
public int serialNumber;public String currentStation;
}
Sample Primary Key Class:public class AlarmClockPK implements java.io.Serializable {
public int serialNumber;public String currentStation;
}
Copyright © 2000, BEA Systems Inc.EJBE-12Developing Enterprise Applications with BEA WebLogic Server
Primary Key AttributesPrimary Key Attributes
§ The EJB class must contain the same parameters listed in the primary key.
AlarmClockBean
••int serialNum;int serialNum;••String currentStation;String currentStation;•long currentVolume;•Date wakeUpTime;•boolean isFm;
AlarmClockPK
••int serialNum;int serialNum;••String currentStation;String currentStation;
Copyright © 2000, BEA Systems Inc.EJBE-13Developing Enterprise Applications with BEA WebLogic Server
CMP EJB CreationCMP EJB Creation
: Client EJBHome instance
create(args)
Container-Provided Classes
EJBObject Entity Context Synchronization database
new
extract container managed fields
create entity representation in DB
ejbCreate(args)
ejbPostCreate(args)
Return remote stub containing primary key
instance!
Create primary key
instance with values
extracted!
Copyright © 2000, BEA Systems Inc.EJBE-14Developing Enterprise Applications with BEA WebLogic Server
Home InterfacesHome Interfaces
§ Entity EJB home interfaces must include one or more find(…) methods.
Syntax for findByPrimaryKey(…) Method:
Syntax for Other find(…) Methods:
Syntax for findByPrimaryKey(…) Method:
Syntax for Other find(…) Methods:
public <RemoteIF> findByPrimaryKey(<PrimaryKey> pk) throws FinderException, RemoteException;
public <RemoteIF> findWhatever(…) throws FinderException, RemoteException;
public Enumeration findWhatever(…)throws FinderException, RemoteException;
Copyright © 2000, BEA Systems Inc.EJBE-15Developing Enterprise Applications with BEA WebLogic Server
Attribute and Attribute and find(…)find(…) Method MappingMethod Mapping
Copyright © 2000, BEA Systems Inc.EJBE-16Developing Enterprise Applications with BEA WebLogic Server
Attribute and Attribute and find(…)find(…) Method MappingMethod Mapping
Copyright © 2000, BEA Systems Inc.EJBE-17Developing Enterprise Applications with BEA WebLogic Server
Finder ExpressionsFinder ExpressionsSyntax for Expressions:
Available Operators:
Available Operands:
Syntax for Expressions:
Available Operators:
Available Operands:
operator operand1 operand2
(), =, <, >, <=, >=, !, &, |, like
1. Another Expression2. An EJB Attribute3. A find(…)Method Parameter (Must precede with $)
Finder Expression Examples:Finder Expression Examples:(> balance $amount)
(& (> bal $amount) (! (= accountType ‘checking’)))
(= 1 1)
(like lastName M%)
Copyright © 2000, BEA Systems Inc.EJBE-18Developing Enterprise Applications with BEA WebLogic Server
Writing the Bean ClassWriting the Bean Class
§ The bean class must implement the EntityBean interface.
The EntityBean Interface:public interface EntityBean extends EnterpriseBean {public void ejbActivate();public void ejbPassivate();public void ejbLoad();public void ejbStore();public void setEntityContext(EntityContext ctx);public void unsetEntityContext()public void ejbRemove();
}
Some Other Guidelines:1. Your ejbCreate(…) methods should return void for CMP.2. You do not have to implement any ejbFind(…) methods for CMP.
The EntityBean Interface:public interface EntityBean extends EnterpriseBean {public void ejbActivate();public void ejbPassivate();public void ejbLoad();public void ejbStore();public void setEntityContext(EntityContext ctx);public void unsetEntityContext()public void ejbRemove();
}
Some Other Guidelines:1. Your ejbCreate(…) methods should return void for CMP.2. You do not have to implement any ejbFind(…) methods for CMP.
Copyright © 2000, BEA Systems Inc.EJBE-19Developing Enterprise Applications with BEA WebLogic Server
Entity EJB Life CycleEntity EJB Life Cycle
does not exist
pooled
ready
instance throws system exception from any method
unsetEntityContext()newInstance()setEntityContext(ec)
ejbStore()ejbLoad()
ejbPassivate()ejbActivate()
ejbFind<METHOD>()
ejbRemove()
ejbCreate(args)ejbPostCreate(args)
business method
Copyright © 2000, BEA Systems Inc.EJBE-20Developing Enterprise Applications with BEA WebLogic Server
PassivationPassivation
: Client EJBHome instance
business method
Container-Provided Classes
EJBObject Entity Context
Synchro-nization database
extract container managed fields
updated entity state in DB
business method
Container
ejbStore()
ejbPassivate()
Copyright © 2000, BEA Systems Inc.EJBE-21Developing Enterprise Applications with BEA WebLogic Server
ActivationActivation
: Client EJBHome instance
business method
Container-Provided Classes
EJBObject Entity Context
Synchro-nization database
set container-managed fields
read entity state in DB
ejbActivate()
Container
ejbLoad()
business method
Copyright © 2000, BEA Systems Inc.EJBE-22Developing Enterprise Applications with BEA WebLogic Server
Standard Entity EJB ExceptionsStandard Entity EJB Exceptions
§ The EJB specification defines five standard EJB application exceptions:Ø javax.ejb.CreateExceptionØ javax.ejb.DuplicateExceptionØ javax.ejb.FinderExceptionØ javax.ejb.ObjectNotFoundExceptionØ javax.ejb.RemoveException
Copyright © 2000, BEA Systems Inc.EJBE-23Developing Enterprise Applications with BEA WebLogic Server
Finally, An Example!Finally, An Example!
§ Let’s write an entity EJB that tracks different alarm clock settings.§ The EJB will track:Ø the time the alarm is supposed to go offØ the current radio station selectedØAM/FM radio selection
Copyright © 2000, BEA Systems Inc.EJBE-24Developing Enterprise Applications with BEA WebLogic Server
The Remote InterfaceThe Remote Interface
The AlarmClock Remote Interface:
public interface AlarmClock extends Remote, EJBObject {public Date getAlarmTime() throws RemoteException;public String getRadioStation() throws RemoteException;public boolean isFmSet() throws RemoteException;public void isFmSet(boolean fm) throws RemoteException;public void setAlarmTime(Date time) throws RemoteException;public void setRadioStation(String station)
throws RemoteException;}
The AlarmClock Remote Interface:
public interface AlarmClock extends Remote, EJBObject {public Date getAlarmTime() throws RemoteException;public String getRadioStation() throws RemoteException;public boolean isFmSet() throws RemoteException;public void isFmSet(boolean fm) throws RemoteException;public void setAlarmTime(Date time) throws RemoteException;public void setRadioStation(String station)
throws RemoteException;}
Copyright © 2000, BEA Systems Inc.EJBE-25Developing Enterprise Applications with BEA WebLogic Server
The Home Interface and Primary KeyThe Home Interface and Primary Key
The AlarmClockHome Home Interface:public interface AlarmClockHome extends EJBHome {AlarmClock create() throws CreateException, RemoteException;AlarmClock create(Date time, String station, boolean fm)
throws CreateException, RemoteException;AlarmClock findByPrimaryKey(AlarmClockPK id)
throws FinderException, RemoteException;Enumeration findAllFMSettings()
throws FinderException, RemoteException;}
The AlarmClockHome Home Interface:public interface AlarmClockHome extends EJBHome {AlarmClock create() throws CreateException, RemoteException;AlarmClock create(Date time, String station, boolean fm)
throws CreateException, RemoteException;AlarmClock findByPrimaryKey(AlarmClockPK id)
throws FinderException, RemoteException;Enumeration findAllFMSettings()
throws FinderException, RemoteException;}
AlarmClockPK Primary Key Class:public class AlarmClockPK implements java.io.Serializable {
public int serialNumber;public String currentStation;
}
AlarmClockPK Primary Key Class:public class AlarmClockPK implements java.io.Serializable {
public int serialNumber;public String currentStation;
}
Copyright © 2000, BEA Systems Inc.EJBE-26Developing Enterprise Applications with BEA WebLogic Server
The Bean Class Finally!The Bean Class Finally!
The AlarmClockBean EJB Class:public class AlarmClockBean implements EntityBean {
public int id;
transient protected EntityContext context;
// Container managed fieldspublic String station;public String wakeUpTime;public boolean isFm;
The AlarmClockBean EJB Class:public class AlarmClockBean implements EntityBean {
public int id;
transient protected EntityContext context;
// Container managed fieldspublic String station;public String wakeUpTime;public boolean isFm;
Copyright © 2000, BEA Systems Inc.EJBE-27Developing Enterprise Applications with BEA WebLogic Server
The Bean Class Finally!The Bean Class Finally!The AlarmClockBean EJB Class Continued:public void ejbActivate() {}public void ejbLoad() {}public void ejbPassivate() {}public void ejbRemove() {}public void ejbStore() {}
public void ejbCreate() {// Generate a unique ID for this EJB.// Most EJBs pass receive this value as a parameter.this.id = (int)(Math.random()*100000);
// Get the station and time from the environment// properties.Properties props = context.getEnvironment();this.station = props.getProperty("Station");this.isFm = props.getProperty("isFM");this.wakeUpTime = props.getProperty("Time");
}
The AlarmClockBean EJB Class Continued:public void ejbActivate() {}public void ejbLoad() {}public void ejbPassivate() {}public void ejbRemove() {}public void ejbStore() {}
public void ejbCreate() {// Generate a unique ID for this EJB.// Most EJBs pass receive this value as a parameter.this.id = (int)(Math.random()*100000);
// Get the station and time from the environment// properties.Properties props = context.getEnvironment();this.station = props.getProperty("Station");this.isFm = props.getProperty("isFM");this.wakeUpTime = props.getProperty("Time");
}
Copyright © 2000, BEA Systems Inc.EJBE-28Developing Enterprise Applications with BEA WebLogic Server
The AlarmClockBean EJB Class Continued:
public void ejbCreate(String time, String station, boolean isFm){// Generate a unique ID for this EJB.// Most EJBs pass this value in.this.id = (int)(Math.random()*100000);
this.wakeUpTime = time;this.station = station;this.isFm = new Boolean(isFm).toString();
}
public void ejbPostCreate() {}public void ejbPostCreate(String time, String station,
boolean isFm) {}
The AlarmClockBean EJB Class Continued:
public void ejbCreate(String time, String station, boolean isFm){// Generate a unique ID for this EJB.// Most EJBs pass this value in.this.id = (int)(Math.random()*100000);
this.wakeUpTime = time;this.station = station;this.isFm = new Boolean(isFm).toString();
}
public void ejbPostCreate() {}public void ejbPostCreate(String time, String station,
boolean isFm) {}
The Bean Class Finally!The Bean Class Finally!EJBE-1, 2
Copyright © 2000, BEA Systems Inc.EJBE-29Developing Enterprise Applications with BEA WebLogic Server
BMP ConsiderationsBMP Considerations
Things you Have to do For BMP Entity EJBs:1. You must code the persistence management for the ejbCreate(…),
ejbRemove(), ejbLoad(), and ejbStore() methods.2. The ejbCreate(…) methods must return a primary key instance.3. The ejbFind(…) methods must be implemented.
Things you Have to do For BMP Entity EJBs:1. You must code the persistence management for the ejbCreate(…),
ejbRemove(), ejbLoad(), and ejbStore() methods.2. The ejbCreate(…) methods must return a primary key instance.3. The ejbFind(…) methods must be implemented.
Copyright © 2000, BEA Systems Inc.EJBE-30Developing Enterprise Applications with BEA WebLogic Server
BMP EJB CreationBMP EJB Creation
: Client EJBHome instance
create(args)
Container-Provided Classes
EJBObject Entity Context Synchronization database
new
create representation in DB
ejbCreate(args)
ejbPostCreate(args)
Return remote stub containing primary key
instance!
Return primary key instance with unique values inserted
Copyright © 2000, BEA Systems Inc.EJBE-31Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-32Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-33Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-34Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-35Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-36Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMP
Copyright © 2000, BEA Systems Inc.EJBE-37Developing Enterprise Applications with BEA WebLogic Server
The Alarm With BMPThe Alarm With BMPEJBE-3
Copyright © 2000, BEA Systems Inc.EJBE-38Developing Enterprise Applications with BEA WebLogic Server
TransactionsTransactions
§ Transactions can group multiple statements into an atomic unit to ensure integrity.§ EJBs can have their transaction
demarcation level set:Ø for the entire EJBØ per method
Copyright © 2000, BEA Systems Inc.EJBE-39Developing Enterprise Applications with BEA WebLogic Server
EJB Transaction AttributesEJB Transaction Attributes
§ The following entities can demarcate transactions:Ø an EJB clientØ the container (automatic demarcation)Ø the EJB component itself
§ The EJB specification defines 6 transaction attributes:Ø TX_NOT_SUPPORTEDØ TX_SUPPORTSØ TX_MANDATORYØ TX-REQUIREDØ TX_REQUIRES_NEWØ TX_BEAN_MANAGED
Copyright © 2000, BEA Systems Inc.EJBE-40Developing Enterprise Applications with BEA WebLogic Server
Container
TX_NOT_SUPPORTEDTX_NOT_SUPPORTED
§ TX_NOT_SUPPORTED transactions cause client transactions to be suspended during the EJB’s execution.
method
EJBContainer
Active Transaction
EJBContainer
Client
1-begin2-method3-commit
method
method
Scenario 1:
Scenario 2: No Transaction Active
Client
Copyright © 2000, BEA Systems Inc.EJBE-41Developing Enterprise Applications with BEA WebLogic Server
TX_SUPPORTSTX_SUPPORTS
§ TX_SUPPORTS implies that the EJB will be included in any client-started transactions.
Container
method
EJBContainer
Active Transaction
EJBContainer
Client
1-begin2-method3-commit
method
method
Scenario 1:
Scenario 2: No Transaction Active
Client
Copyright © 2000, BEA Systems Inc.EJBE-42Developing Enterprise Applications with BEA WebLogic Server
TXTX__MANDATORYMANDATORY
§ TX_MANDATORY transactions require the client to pass a global transaction to the EJB.
Container EJBContainer
Active Transaction
EJBContainer
Client
1-begin2-method3-commit
method
method
Scenario 1:
Scenario 2: No Transaction Active
Client
TransactionRequiredException
Copyright © 2000, BEA Systems Inc.EJBE-43Developing Enterprise Applications with BEA WebLogic Server
TX_REQUIREDTX_REQUIRED
§ TX_REQUIRED transactions force the EJB to be executed within a transaction started either by the client or the container.
Container EJBContainer
Active Transaction
Container
Client
1-begin2-method3-commit
method
method
Scenario 1:
Scenario 2: No Transaction Active
Client
1-begin2-method3-commit
EJB
Copyright © 2000, BEA Systems Inc.EJBE-44Developing Enterprise Applications with BEA WebLogic Server
TX_REQUIRES_NEWTX_REQUIRES_NEW
§ TX_REQUIRES_NEW transactions force the EJB to execute within a new transaction that can only be started by the container.
Container EJBContainer
Active Transaction
Container
Client
1-begin2-method3-commit
method
Scenario 1 (try to avoid):
Scenario 2:No Transaction Active
Client
1-begin2-method3-commit
EJB
1-begin2-method3-commit
Localized Transaction
Copyright © 2000, BEA Systems Inc.EJBE-45Developing Enterprise Applications with BEA WebLogic Server
TX_BEAN_MANAGEDTX_BEAN_MANAGED
§ TX_BEAN_MANAGED transactions are demarcated within the EJB only.
Container EJBContainer
Active Transaction
Container
Client
1-begin2-method3-commit
method
Scenario 1 (try to avoid):
Scenario 2:No Transaction Active
Client
1-begin2-method3-commit
Localized Transaction
method
EJB1-begin2-method3-commit
method
Copyright © 2000, BEA Systems Inc.EJBE-46Developing Enterprise Applications with BEA WebLogic Server
The The UserTransactionUserTransaction InterfaceInterface
§ Use the javax.jts.UserTransactionobject to demarcate transactions within a client or EJB.
UserTransaction
begin()commit()rollback()setRollbackOnly()getStatus()setTransactionTimeout()
<<Interface>>
To Obtain a New javax.jts.UserTransaction Instance From JNDI:To Obtain a New javax.jts.UserTransaction Instance From JNDI:UserTransaction trans =
(UserTransaction)ctx.lookup(“javax.jts.UserTransaction”);
Copyright © 2000, BEA Systems Inc.EJBE-47Developing Enterprise Applications with BEA WebLogic Server
Other Transaction IssuesOther Transaction Issues
§ An EJB’s conversational state is NOTencompassed in a transaction.§ A rollback() on a transaction that
encompasses an EJB will not revert the EJB’s attributes!§ Container and client managed transaction
objects can be accessed by the context:
To Obtain Change the Status of the Current Transaction Within an EJB:To Obtain Change the Status of the Current Transaction Within an EJB:contextObject.setRollbackOnly();boolean setForRollback = contextObject.getRollbackOnly();
Copyright © 2000, BEA Systems Inc.EJBE-48Developing Enterprise Applications with BEA WebLogic Server
Reverting Conversational StateReverting Conversational State
§ You can have your EJB implement the SessionSynchronization interface.
SessionSynchronization Interface Methods:// Called by the application server right after the start of a new transaction. If you // store attributes that may need to be reverted, do it here.public void afterBegin();
// Called immediately before the completion of the transaction. It is NOT known if// is committed or rolled back at this point.public void beforeCompletion();
// Called immediately after the completion of a transaction. If the committed// variable is true, then the transaction was successful. If the committed value// is false, the transaction was rolled back. You can recover EJB state from // within this method if you need to.public void afterCompletion(boolean committed);
}
SessionSynchronization Interface Methods:// Called by the application server right after the start of a new transaction. If you // store attributes that may need to be reverted, do it here.public void afterBegin();
// Called immediately before the completion of the transaction. It is NOT known if// is committed or rolled back at this point.public void beforeCompletion();
// Called immediately after the completion of a transaction. If the committed// variable is true, then the transaction was successful. If the committed value// is false, the transaction was rolled back. You can recover EJB state from // within this method if you need to.public void afterCompletion(boolean committed);
}
Copyright © 2000, BEA Systems Inc.EJBE-49Developing Enterprise Applications with BEA WebLogic Server
ReviewReview
§ In this section we talked about :Ø container-managed and bean-managed
persistenceØ the differences between session and entity
EJBsØ primary key classesØ transactions and their demarcation levels
Copyright © 2000, BEA Systems Inc.EJBE-50Developing Enterprise Applications with BEA WebLogic Server
ReviewReview
§ In this module we talked about:Ø container and bean managed persistenceØ primary key classesØ differences between session and entity EJBsØwriting ejbPostCreate(…) and ejbFind(…) methods
Øwriting ejbLoad() and ejbStore()methods
Ø transactions