Title: Enterprise Java Beans
1Enterprise Java Beans
2Topics
- Entity Bean Overview
- Bean Managed Persistence
- Container Managed Persistence
- Weblogic Extensions
- Resources
- References
3Enterprise Bean
- Component that can be deployed in any
EJB-compliant application server - Remote interface for its operations
- extends EJBObject
- Home Interface for create, find, and remove
- Bean Implementation
- implement SessionBean or EntityBean
- Required container lifecycle callbacks
- implement business methods
4Bean Types
- Session Beans
- Represents business logic operations
- Teller and transfer()
- Stateless and Stateful
- Exist for lifetime of client session
- Entity Beans
- Represents persistent data in a database
- Exist indefinitely
- Bean-managed and Container-managed persistence
5Container and Beans
Home Interface
Container
Pool
Home
Home Stub
create
Client
Remote Object Stub
EJBObject
Account Bean
transfer
Remote Interface
6Entity Bean (from 1.1 spec)
- Provides an object view of data in the database
- Allows shared access from multiple users
- Can be long-lived (lives as long as the data in
the database) - The entity, its primary key, and its remote
reference survive the crash of the EJB container
7Entity Bean Support
- Optional in EJB 1.0
- Required in EJB 1.1
8Bean Characteristics
9Creating a Customer Entity Bean
- Create the Primary Key Class
- Create the Business Interface
- Create the Remote Object Interface
- Create the Home Interface
- Create the Bean Class
- Create the Deployment Descriptor
10(No Transcript)
11(No Transcript)
12(No Transcript)
13(No Transcript)
14PrimaryKey Class
- Two Objects are considered the same if they have
the same Home and their PrimaryKey objects are
equal - PrimaryKey classes
- single primary keys can be mapped to existing
classes (e.g. String) - compound primary keys must be encapsulated by a
custom class - key values
- must be legal RMI-IIOP types
- must match in type and name with declaration in
the bean class - must be public
- class must implement a Default Constructor,
hashCode() and equals() methods - must be Serializable
15Create the PrimaryKey Class
- public class CustomerPK implements
java.io.Serializable - public name
- public CustomerPK()
//this
one is required - public CustomerPK(String name)
this.name name //this on is convenient - public int hashCode()
return name.hashCode() - public boolean equals(Object rhs)
- try
- return ((CustomerPK)rhs).name.equals(name
) -
- catch (Exception ex)
- return false
-
-
16Business Interface
- Defines the business methods to be implemented by
the Bean - Is implemented by the Remote Object and Bean
Classes - Methods must declare throws java.rmi.RemoteExcept
ion - Arguments and return types must be legal RMI-IIOP
types - Does NOT extend java.rmi.Remote
- doing so makes the Bean Class a Remote Object
(bad) - Does NOT extend any EJB Interfaces
- doing so would limit its use to only that type of
object
17Create the Business Interface
- public interface CustomerBI
- public String getName() throws
java.rmi.RemoteException - public String getAddress() throws
java.rmi.RemoteException
18Remote Object Interface
- Must extend javax.ejb.EJBObject
- Extends Business Interface
- Define the Remote Object Interface
- public interface Customer extends
javax.ejb.EJBRemote, -
CustomerBI -
19Home Interface
- Extends javax.ejb.EJBHome
- create() and create( args )
- creates row in database
- optional with entity beans
- must have matching create() and ejbCreate()
methods in bean implementation if present - find()
- findByPrimaryKey() is mandatory
- other finders can be implemented
- ex. Customer findByName(String name)
- ex. Collection findAllByLikeName(String name)
- EJB 1.0 find methods return java.util.Enumeration
- EJB 1.1 allows java.util.Enumeration and
java.util.Collection
20Create Home Interface
- public class CustomerHome extends
javax.ejb.EJBHome - Customer create(String name, String address)
- throws javax.ejb.CreateException,
RmiException - Customer findByPrimaryKey(Customer pkey)
- throws javax.ejb.FinderException,
java.rmi.RemoteException - javax.util.Collection findAllByLikeName(String
name) - throws javax.ejb.FinderException,
java.rmi.RemoteException
21Creation Example
- Context ic getInitialContext()
- CustomerHome ch (CustomerHome)
- javax.rmi.PortableRemoteObject.narrow(ic.lookup
(CustomerHome), -
CustomerHome.class) - Customer c ch.create(Dan, Pasadena )
- String name c.getName() // Dan
- // Can receive finderException or RemoteException
- c ch.findByPrimaryKey(new CustomerPK(Dan))
- name c.getName() // Dan
- javax.util.Collection customers
ch.findAllByLikeName(D) - //converted to D by finder method
22Create the Bean Class
- public class CustomerBean implements
javax.ejb.EntityBean, -
CustomerBI - //these must be public in CMP implementations
- public String name
- public String address
-
- private javax.ejb.EntityContext entityCtx_
- //called after the bean is instantiated and
prior to being placed in the bean pool - public void setEntityContext(javax.ejb.EntityCo
ntext ctx) - entityCtx_ ctx //can now inspect the
beans environment (ex. jndi) -
- //called when the bean is removed from the
bean pool and prior to leaving JVM - public void unsetEntityContext() entityCtx_
null
23Implement the Bean Class Business Methods
- public getName()
- return name
-
- public getAddress()
- return address
-
- Real business methods can be much more complicated
24Implement Bean ClassCreate/Remove Methods
- //called prior to creating the Remote Object and
inserting into the database - public CustomerPK ejbCreate(String name, String
address) - this.name name
- this.address address
- return null //per spec
-
- //called after associating with Remote Object and
stored in database - public void postCreate(String name, String
address) - //called before object dis-associated from Remote
Object and removed from database - public void ejbRemove()
25Implement Bean ClassResource Management Methods
- //Called after associated with a
RemoteObject/removed from the bean pool and - // placed in the cache. Its not yet synchronized
with database - public void ejbActivate()
- //allocate any resources required for object
-
- //Called prior to dis-associating from
RemoteObject/returning the instance back to - // the bean pool and removing from cache. It has
already been synchronized with - // the database.
- Public void Passivate()
- //release any allocated resources
-
26Implement Bean ClassDatabase Synchronization
Methods
- //Called at the start of a transaction, prior to
the business method invocation - public ejbLoad()
- //CMP - process public attributes that have
been synchronized from the database - //BMP - obtain database connection and
manually synchronize from database -
- //Called at the end of a transaction when
container recognizes bean state change. - // weblogic augments this behavior with an
isDirty() inspector. - public void ejbStore()
- //CMP - prepare public attributes for
synchronization to the database - //BMP - obtain database connection and
manually synchronize to database
27Implement Bean Class Finder Methods (BMP)
- //Container returns Customer Remote Object to
client - public CustomerPK ejbFindByPrimaryKey(CustomerPK
key) - throws FinderException
-
- // Perform database select statement to see if
key.name is present - // if present return primary key, else throw
FinderException -
- public javax.util.Collection ejbFindAllByLikeName(
String name) -
- // Perform database select statement to locate
all like matches -
- CMP finder methods are defined in the deployment
descriptor and implemented by the Containers EJB
compiler
28Create Deployment Descriptor(ejb-jar.xml)
-
- Inc.//DTD Enterprise JavaBeans 1.1//EN'
'http//java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd' -
-
- This component is used to track basic
information about Customers. -
-
- Customer Component
- ...
29Define the Individual Beans
-
-
- This bean is used to track the individual
state of each Customer. -
- Customer Bean
-
- Customer
30Define the Interface and Classes
-
- ejava.ejb.estore.CustomerHome
-
- ejava.ejb.estore.personnel.Customerote
-
- ejava.ejb.estore.CustomerBeanass
-
- Container
31Define the PrimaryKey Class
-
- ejava.ejb.estore.CustomerPKm-key-class
-
- True
32Define the Container ManagedFields (CMP)
33Define Environment Properties
-
-
- This is a sample env
entry. - sample
- java.lang.Stringype
- Sample Environment
Value -
34Define EJB References
35Define Security Role ReferencesHard Coded into
the Bean Class
36Define Resource ReferencesHard Coded into the
Bean Class
37Define Security Roles
-
-
-
-
- Allowed read/write to
obejcts - Admin
-
-
- Allowed read-only access to
objects - User
-
38Define Method Restrictions
-
- These are the writable
methods. - Admin
-
-
- Customer
-
- Home
- create
-
-
- java.lang.Stringam
- java.lang.Stringam
-
-
39Define Method Restrictions
-
- These are the read-only
methods - Admin
- User
-
- Customer
-
-
-
40Define Transaction Properties
41Define Client Jar File
42Entity Bean Resource Management
- Bean instances are managed by the container to
conserve resources and increase performance - pooling, caching
- Our CustomerBean must implement required
lifecycle callbacks - mimic CustomerHome create,find,remove
- implement EntityBean
- Cache
- Activation/Passivation
43Database Synchronization
- As with all EJBs, only a single thread can be
running within a bean instance - Multiple entity bean instances can be created to
represent same data in database - Consistency ?
- ejbLoad() and ejbStore() are called to
synchronize bean with underlying storage
44State Management
- State synchronization methods
- ejbLoad
- ejbStore
- Resource Management methods
- ejbActivate
- ejbPassivate
45Entity Bean Lifecycle
- Does Not Exist
- Just in the jar file. Before creation or after
finalization - Pooled
- Exists but does not represent any particular
database entity i.e. not associated with an
EJBObject - service find() requests
- Ready
- assigned to an EJBObject
- can handle client request for specific PK
46Lifecycle (Cont)
- Bean callback methods are invoked as the
container moves the bean instance through these
states - Action required depends on entity bean type
- Container Managed Persistence (CMP)
- Bean Managed Persistence (BMP)
47Entity Bean Types
- Bean can have total control over loading and
storing from database - Bean Managed Persistence (BMP)
- Container can take over this responsibility
- Container Managed Persistence (CMP)
- Specialized Implementations
- Toplink for relational databases
- CICS
48Bean Managed Persistence
49Bean Managed Persistence (BMP)
- The CustomerBean used BMP
- implemented all database interaction
- create, remove, and find
- Have to do object-relational mapping
- Synchronize bean state with database when
requested by container
50Creation
- Container populates pool with unassociated bean
implementations - calls no-argument constructor
- sets entity context
- Client calls create on home
- create sent to bean impl. Populates attributes
and inserts row in database - EJBObject created for client
51Creation (Cont)
- Bean implementation is associated with EJBObject
- ejbPostCreate() called on bean instance
- bean is now in the ready state
- Client invokes business method on EJBObject
- EJBObject manages security, transactions, etc.
- Call delegated to bean instance
52(No Transcript)
53Removal
- Client calls remove on Home or EJBObject
- Container manages security, transactions, etc.
- remove delegated to beans ejbRemove() method
- removes data from database
- bean moves to pooled state
54(No Transcript)
55State Synchronization
- When in the ready state, beans frequently need to
be synchronized with the underlying data store - typically at transactional boundaries
- ejbLoad() is called when bean state needs to
re-read from database - ejbStore() is called when bean state needs to be
written to database
56(No Transcript)
57Load and Store
- ejbLoad
- Use EntityContext.getPrimaryKey()
- read attributes from database
- ejbStore
- write attributes to database
- Only occur when the bean is in the ready state
- Associated with an EJBObject/PrimaryKey
58Activation and Passivation
- Beans can be moved to the pooled state
- Passivation
- A few bean instance can service many clients
- As a result of a remove() call
- Can transition from pooled to ready state
- create()
- find()
- activation()
59(No Transcript)
60Activation and Passivation
- When Passivated, bean should give up any
resources held on behalf of the data represented
by the Primary Key - When Activated, bean can acquire and resources
specific to the Primary Key
61BMP Summary
- Have to handle all database interaction
- except transactions
- ejbLoad() and ejbStore() called when bean
instance state must be synchronized with database - ejbActivate() and ejbPassivate() called when bean
is moved between the ready state and pooled state
62Container Managed Persistence
63Container Managed Persistence CMP
- Controlled by deployment descriptor
- Create, find, and remove can be implemented by
the container - Container can synchronize bean state and the
database for us - Affects lifecycle operations
- Callbacks tell us something has occurred vs. you
must do something now
64CMP Creation
- Notification that instance is about to be created
in database - Simply need to set attributes
- public CustomerPK ejbCreate( String name, String
address ) -
- this.name name
- this.address address
- return null
65CMP Creation (Cont)
- ejbPostCreate( String name, String address )
- called after association with EJBObject
- EntityContext is now meaningful
- action is not required
66(No Transcript)
67CMP Remove
- Notification that client is removing the data for
the associated Primary Key. - Prepare for removal
- Container will actually remove the data from the
database
68(No Transcript)
69State Synchronization
- Synchronize bean state with database
- Usually at transactional boundaries
- ejbLoad and ejbStore invoked by container
- CMP
- Informational message that container has either
- just loaded state from database
- is ready to store state to database
- Opportunity to pre or post-process attributes
70(No Transcript)
71Activation/Passivation
- Resource Management
- Called when bean is moved from ready state to
pooled state. - Disassociated with EJBObject/Primary Key
- Release/Acquire resources for specific entity
72CMP Finders
- Declared in home interface
- Implementation can be automatically generated by
the container
73Define Weblogic CMP descriptor(weblogic-cmp-rdbms
-jar.xml)
- "-//BEA Systems, Inc.//DTD WebLogic 5.1.0 EJB
RDBMS Persistence//EN" - "http//www.beasus/com/weblogic-rdbms-persistence
.dtd" -
- demoPool
- ejbAccounts
-
74Define Attribute Mapping
75Define Finder Methods
-
- findAllByLikeName
-
- java.lang.Stringam
-
-
-
-
-
- 0
- "" _at_0
"" - java.lang.Stringsion-type
-
-
76CMP Summary
- Eliminates a lot of code, but capability is still
limited - less code means fewer bugs
- Problems
- persistence declaration not sufficiently
standardized - many containers can only map a bean to one table
77Entity Bean Performance Issues
78Performance Issues
- When could Entity Beans be expensive
- CMP performs eager database synchronization on
each transaction - BMP allows for lazy database synchronization
- Who should call the Entity Beans Remote methods
? - Clients should call session bean operations that
operate on persistent data - Should you utilize entity beans at all ?
- Performance hit - all calls go through the
container via the EJBObject - Higher performance going directly to the
databases vs. functionality of container
79Weblogic Extensions
80Weblogic Extensions (5.1)
- isDirty
- limits calls to ejbStore
- Read-only entity beans
- Do not support transactions
- Container can call ejbLoad at configurable time
intervals - Database is shared
- Must be false when clustering is enabled
81Create Weblogic DelpoymentExtensions
(weblogic-ejb-jar.xml)
-
- Systems, Inc.//DTD WebLogic 5.1.0 EJB//EN'
'http//www.bea.com/servers/wls510/dtd/weblogic-ej
b-jar.dtd' -
-
-
- Customer
82Define Caching Properties
83Define Persistence
-
-
- isDirtyfied-method-name
-
- Truey-updates-until-end-of-tx
-
- False-ejbload
84Define Persistence (cont.)
-
-
- WebLogic_CMP_RDBMSntifier
- 5.1.0
- META-INF/weblogic-cmp-rdbms-jar
.xml -
-
- False
85Define Persistence (cont.)
-
-
-
-
- WebLogic_CMP_RDBMSype-identifier
- 5.1.0
-
-
86Define Clustering Properties
87Define Generic Transaction Properties
88Define Resource Reference Mapping
89Define the JNDI Mapping for EJBHome
-
- Trueby-reference
-
- CustomerHome
90Define Security Role Mappings
91Entity Bean 1.1 Changes
- Now required to be EJB 1.1 compliant
- Entity Beans can not programmatically start
transactions (via JTS) - create() signature for BMP entity beans
- returns null instead of void
- find methods must throw FinderExceptions
92Entity Bean Summary
- Models persistent state in database
- Facilitates declarative persistence
- BMP vs. CMP
- Performance implications
- wrap calls to entity beans with session beans
93Resources
- Main EJB Page
- http//java.sun.com/products/ejb/
94References
- Developing Java Enterprise Applications. Asbury,
Weiner. Wiley. 1999 - Java Enterprise in a Nutshell. Flanagan et al.
OReilly 1999 - Mastering Enterprise JavaBeans and the Java 2
Platform, Enterprise Edition. Roman. Wiley. 1999 - EJB 1.1 Specification
- Java Report. Whats new in EJB 1.1?,
Monson-Haefel. August 1999.