Transcript ejb-ref

Enterprise
Java
Entity Beans
Container and Bean Managed Persistence
v041102
Entity Beans
1
Topics
Enterprise
Java
• Understanding Entity Beans
• Implementing Entity Beans
– Container Managed Persistence
– Bean Managed Persistence
v041102
Entity Beans
2
Enterprise
Java
Understanding Entity Beans
v041102
Entity Beans
3
Enterprise Bean
Enterprise
Java
• Component that can be deployed in any EJB-compliant
application server
• Component interface for its operations (Remote and Local)
• Home Interface for create, find, and remove (Remote and
Local)
• Bean Implementation
– implements business methods
– implements finder (BMP Entity), home (2.0 Entity), and Select
(2.0 CMP Entity) methods
v041102
Entity Beans
4
Bean Types
Enterprise
Java
• Entity Beans
– Represents persistent data in a database
• Account and deposit()
– Exists indefinitely
– Bean-managed and Container-managed persistence
• Session Beans
– Represents business logic operations
• Teller and transfer()
– Stateless and Stateful
– Exist for lifetime of client session
v041102
Entity Beans
5
Bean Types
Enterprise
Java
• Message Beans
– Stateless component invoked using asynchronous
message (JMS)
v041102
Entity Beans
6
Enterprise
Java
Container and Beans
create
find
JVM
Container
Remote Home Stub
Remote Home
Remote Object Stub
Remote Object
Remote
Client
deposit
transfer
v041102
Local Home
Local
Client
Entity Beans
EJB
Class
EJB
Class
EJB
Class
Bean Pool
Local Object
7
Entity Bean (from Spec)
Enterprise
Java
• 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
v041102
Entity Beans
8
Entity Bean Support
Enterprise
Java
• Optional in EJB 1.0
• Required in EJB 1.1
• Revised in EJB 2.0
– Added Abstract Schemas
– Added EJB Query Language which is portable across different database
technologies (even though it is similar to SQL)
– Added Container Managed Relationships
– EJB 1.1 support still a requirement in EJB 2.0
• EJB 2.1
– J2EE 1.4, timers, ELB-QL updates
• EJB 3.0 radical changes (early draft review)
–
–
–
–
v041102
Annotations for persistence mappings
No home or component interface
Hibernate-inspired
Not an abstract class
Entity Beans
9
Entity Bean Lifecycle
Enterprise
Java
Does Not Exist
unload bean
instance()/unsetEntityContext();
finalize()
bean instance
required/Class.newInstance();
setEntityContext()
Pooled
passivate object()/ejbPassivate
this.ejbSelect()
Home.find()/ejbFind()
Home.XXX()/ejbHomeXXX()
Home.create()/ejbCreate();
ejbPostCreate()
object.remove()/ejbRemove()
activate object()/ejbActivateObject
Ready
object.method()/ejbLoad();
business method(); ejbStore()
v041102
this.ejbSelect()
Entity Beans
10
Entity Bean States
Enterprise
Java
• Does Not Exist
– no instance instantiated
– default state at container startup
• Pooled
– state entered when container offers component
– state re-entered when object disassociated from bean
• Ready
– state where business methods can be invoked
v041102
Entity Beans
11
Entity Bean Transitions
Enterprise
Java
• Does Not Exist -> Pooled
– methods invoked
• Class.newInstance() (default constructor)
– usually not provided/no behavior
– place all bean initialization code in setEntityContext and
object initialization in ejbCreate/ejbPostCreate
• setEntityContext(EntityContext ctx)
– establish EJB’s reference to container (ctx)
v041102
Entity Beans
12
Entity Bean Transitions
Enterprise
Java
• Pooled -> Ready (via creation)
– occurs when client invokes a Home.create(<args>)
– object created, bean instance located
– methods invoked
• ejbCreate(<args>)
– may establish properties
– must establish primary key
– object not yet ready to be advertised
• ejbPostCreate(<args>)
– establish relationships (object ready to be advertised)
v041102
Entity Beans
13
Entity Bean Transitions
Enterprise
Java
• Pooled -> Ready (via query)
– occurs when Home.find (<args) or
this.ejbSelect(<args>) invoked to return objects
– bean selected from pool, associated with object
– methods invoked
• ejbActivate()
– called after object associated with bean instance
– no transaction or security context
– no interaction with database
v041102
Entity Beans
14
Entity Bean Transitions
Enterprise
Java
• Ready -> Pooled (passivation)
– occurs after ejbStore() and just prior to disassociating
object from bean
– bean returned to pool
– methods invoked
• ejbPassivate()
– simply a notification
– no state serialized as in Stateful Session Beans
– no interaction with database
v041102
Entity Beans
15
Entity Bean Transitions
Enterprise
Java
• Ready -> Pooled (removal)
– occurs when client invokes object.remove()
– bean returned to pool
– methods invoked
• ejbRemove()
– must release any object-specific resources (identical to
ejbPassivate())
» may call ejbPassivate() within ejbRemove()
– called prior to database removal in CMP
– called to remove from database in BMP
v041102
Entity Beans
16
Entity Bean Transitions
Enterprise
Java
• Ready State
– occurs when client invokes object.<business method>()
– bean activated from pool
– methods invoked
• ejbLoad()
– synchronize cache with database (read from database)
– called after db load in CMP; command to load in BMP
• business method
• ejbStore()
– synchronize cache with database (write to database)
– called prior to db store in CMP; command to store in BMP
v041102
Entity Beans
17
Enterprise
Java
Implementing CMP Entity Beans
v041102
Entity Beans
18
Creating a Book CMP Entity Bean
Enterprise
Java
• (Create the Primary Key Class)
– if required
• Create Value Objects
• Create the Local/Remote Object Interface
– *Entity Beans should only be accessed by Session
Facades through their local interfaces
• Create the Local/Remote Home Interface
• Create the Bean Class
• Create the Deployment Descriptors
v041102
Entity Beans
19
...ejb.entity.bean.BookEJB
java.lang.String
Entity Bean Class
Enterprise
Java
-ctx_:EntityContext
-PRINT_DEBUG:boolean
+ejbActivate:void
+ejbPassivate:void
+ejbLoad:void
+ejbStore:void
+ejbRemove:void
+setEntityContext:void
+unsetEntityContext:void
#log:void
id:String
author:String
title:String
topic:String
container.BookEJB_Impl
<abstract method impls>
<concrete method interpose>
+ejbCreate:String
+ejbPostCreate:void
+ejbCreate:String
+ejbPostCreate:void
+setId:void
+getId:String
+setAuthor:void
+getAuthor:String
+setTitle:void
+getTitle:String
+setTopic:void
+getTopic:String
v041102
Entity Beans
20
EJBContext
interface
javax.ejb.EJBContext
interface
javax.ejb.SessionContext
+getCallerIdentity:java.security.Identity
+getCallerPrincipal:java.security.Principal
+getEJBHome:javax.ejb.EJBHome
+getEnvironment:java.util.Properties
+getRollback Only:boolean
+getUserTransaction:javax.transaction.UserTransaction
+isCallerInRole:boolean
+isCallerInRole:boolean
+setRollback Only:void
callerIdentity:java.security.Identity
callerPrincipal:java.security.Principal
EJBHome:javax.ejb.EJBHome
environment:java.util.Properties
rollbackOnly:boolean
userTransaction:javax.transaction.UserTransaction
v041102
Enterprise
Java
Entity Beans
+getEJBObject:javax.ejb.EJBObject
EJBObject:javax.ejb.EJBObject
interface
javax.ejb.EntityContext
+getEJBObject:javax.ejb.EJBObject
+getPrimaryKey:java.lang.Object
EJBObject:javax.ejb.EJBObject
primaryKey:java.lang.Object
21
PrimaryKey Class
Enterprise
Java
• Uniquely Identifies Object within database
• Two Objects are considered the same if they have
the same Home and their PrimaryKey objects are
equal
• Single primary keys can be mapped to java.lang
classes (e.g. java.lang.String)
• Single primary keys may optionally be
implemented with a custom Primary Key Class
• Compound primary keys must be implemented
with a custom Primary Key Class
v041102
Entity Beans
22
PrimaryKey Classes
Enterprise
Java
• 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
v041102
Entity Beans
23
Create the PrimaryKey Class
Enterprise
Java
package corej2ee.examples.entitybooks;
import java.io.Serializable;
public class BookPK implements Serializable {
public String id;
public BookPK()
{}
//this one is required
public BookPK(String id) { this.id = id; } //this one is optional
public String toString() { return id; }
public int hashCode()
{ return id.hashCode(); }
public boolean equals(Object rhs) {
try { return ((BookPK)rhs).id.equals(id); }
catch (Throwable ex) { return false;}
}
}
v041102
Entity Beans
24
Value Objects
Enterprise
Java
• Used to transfer data between the EJB Tier and
client-tiers
• Pass-by-Value semantics
• Also called “Data Transfer Objects” (DTOs)
• Very similar to structs
• Used by bulk accessors
– bulk accessor interfaces usually declared in Session
Façade Remote
v041102
Entity Beans
25
Create Book Value Objects
Enterprise
Java
package corej2ee.examples.entitybooks;
import java.io.Serializable;
public class Book implements Serializable {
private String id_; private String title_;
private String author_; private String topic_;
public Book() {}
public Book(String id, String title, String author, String topic) {
id_ = id;
title_ = title; author_ = author; topic_ = topic; }
public String getId()
{ return id_; }
public String getTitle()
{ return title_; }
...
public void setTitle(String title) { title_ = title; }
...
}
v041102
Entity Beans
26
Object Interface
Enterprise
Java
• Defines the business methods to be implemented
by the Bean that can be invoked by a client
• Arguments and return types must be legal RMIIIOP types
• Local Interface
– fine-grain access from Session Façade
• Remote Interface
– larger-grain bulk accessors
v041102
Entity Beans
27
Local Object Interface
Enterprise
Java
• Must extend javax.ejb.EJBLocalObject
• Methods may not throw
javax.ejb.RemoteException
package corej2ee.examples.entitybooks.ejb;
public interface BookLocal extends javax.ejb.EJBLocalObject {
String getId();
String getTitle();
String getAuthor();
String getTopic();
void setTitle(String title);
void setAuthor(String author);
void setTopic(String topic);
}
v041102
Entity Beans
28
Remote Object Interface
Enterprise
Java
• Must extend javax.ejb.EJBObject
• Methods throw java.rmi.RemoteException
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface BookRemote extends EJBObject {
Book getValues() throws RemoteException;
void setValues(Book values) throws RemoteException;
}
v041102
Entity Beans
29
Home Interface
Enterprise
Java
• create<Suffix>() and create<Suffix>( args )
– creates row in database
– optional with entity beans
– must have matching ejbCreate<Suffix>() and ejbPostCreate<Suffix>()
methods in bean implementation if present
• find()
– findByPrimaryKey(<primary key class>) is mandatory
– other finders can be implemented
• ex. findByName(String firstName, String lastName);
• ex. findByAddress(String address);
– return types include java.util.Collection and java.util.Set
• <home methods>() - work on table as a whole
v041102
Entity Beans
30
Create Local Home Interface
Enterprise
Java
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
public interface BookLocalHome extends EJBLocalHome {
BookLocal create(String id) throws CreateException;
BookLocal create(String id, String title, String author, String topic)
throws CreateException;
BookLocal findByPrimaryKey(String pk) throws FinderException;
Collection findAll() throws FinderException;
}
v041102
Entity Beans
31
Local Creation Example
Enterprise
Java
InitialContext jndi = new InitialContext();
BookLocalHome bHome =(BookLocalHome)
jndi.lookup("java:comp/env/ejb/BookLocalHome");
BookLocal bookLocal = bHome.create(
book.getId(), book.getTitle(), book.getAuthor(), book.getTopic());
v041102
Entity Beans
32
Create Remote Home Interface
Enterprise
Java
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EJBHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.rmi.RemoteException;
import java.util.Collection;
public interface BookRemoteHome extends EJBHome {
BookRemote create(String id) throws CreateException, RemoteException;
BookRemote create(Book values)
throws CreateException, RemoteException;
BookRemote findByPrimaryKey(String pk) throws FinderException;
Collection findAll() throws FinderException, RemoteException;
}
v041102
Entity Beans
33
Remote Creation Example
Enterprise
Java
InitialContext jndi = new InitialContext();
BookRemoteHome bHome =(BookRemoteHome)
PortableObjectRemote.narrow(
jndi.lookup("java:comp/env/ejb/BookRemoteHome"),
BookRemoteHome.class);
BookRemote bookRemote = bHome.create(book);
v041102
Entity Beans
34
Create the Bean Class
Enterprise
Java
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
public abstract class BookEJB implements EntityBean {
/** This is our reference into the container. */
private EntityContext ctx_;
…
}
v041102
Entity Beans
35
Define the Abstract Accessors
Enterprise
Java
public abstract void setId(String id);
public abstract String getId();
public abstract void setAuthor(String author);
public abstract String getAuthor();
public abstract void setTitle(String title);
public abstract String getTitle();
public abstract void setTopic(String topic);
public abstract String getTopic();
v041102
Entity Beans
36
Implement the Bean Class
Business Methods
Enterprise
Java
public Book getValues() {
return new Book(getId(), getTitle(), getAuthor(), getTopic());
}
public void setValues(Book values) {
setTitle(values.getTitle());
setAuthor(values.getAuthor());
setTopic(values.getTopic());
}
v041102
Entity Beans
37
Coordinate Access to Container
Enterprise
Java
/** This method is invoked after the bean class is instantiated and just
prior to being available in the pool. The bean should acquire any
object-neutral resources at this point. Note that the bean is not
associated with an object at this point and any calls to the
context's getPrimaryKey() will result in an exception. */
public void setEntityContext(EntityContext ctx) { ctx_ = ctx; }
/** This method is invoked just after removing the bean from the pool and
finalizing it. The bean should release any object-neural resources at
this point. Note that the bean is not associated with an object at
this point and any attempt to access the primary key or abstract data
model will result in an error. */
public void unsetEntityContext() { ctx_ = null; }
v041102
Entity Beans
38
Implement Bean Class
Create Methods
Enterprise
Java
/**
This method must set the primary key for the object and optionally
set any of the fields that will get mapped into the database. */
public String ejbCreate(String id) throws CreateException {
setId(id);
return null; //container gets primary key another way
}
/**
This method is where we establish any relationships to our object. */
public void ejbPostCreate(String id) {}
v041102
Entity Beans
39
Implement Bean Class
Create Methods (cont.)
Enterprise
Java
public String ejbCreate(String id, String title, String author, String topic)
throws CreateException {
setId(id);
setTitle(title);
setAuthor(author);
setTopic(topic);
return null; //container gets primary key another way
}
public void ejbPostCreate(
String id, String title, String author, String topic) {
}
v041102
Entity Beans
40
Implement Bean Class
Remove Method
Enterprise
Java
/**
This method is called just before the row(s) representing the
abstract data model get removed from the database.
*/
public void ejbRemove() {
log("BookEJB.ejbRemove:" + getId() + ":" + getTitle());
}
v041102
Entity Beans
41
Implement Bean Class
Resource Management Methods
Enterprise
Java
/** This method is invoked just after the bean is associated with an
object. We have a primary key, but out abstract data model has not
yet been synchronized with the database. We can allocate any
object-specific resources (that do not depend on the database values)
at this point. */
public void ejbActivate() {}
/** This method is invoked just prior to disassociating the object from
the bean. The state of the abstract data model has already been
synchronized with the database. We should release any object-specific
resources as this point. */
public void ejbPassivate() { }
v041102
Entity Beans
42
Implement Bean Class
Database Synchronization Methods
Enterprise
Java
/**
This method is called just after the abstract data model has been
restored from the database. This method should prepare any transient
variables for use by the business methods as this time. */
public void ejbLoad() { }
/**
This method is called just before the abstract data model gets stored
to the database. This method should prepare the abstract data model
variables for their stored state. */
public void ejbStore() { }
v041102
Entity Beans
43
Create Deployment Descriptor
(ejb-jar.xml)
Enterprise
Java
<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans
2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>BookCMP</ejb-name>
...
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
...
</container-transaction>
</ejb-jar>
v041102
Entity Beans
44
Define the Individual Beans
Enterprise
Java
<entity>
<ejb-name>BookCMP</ejb-name>
<home>corej2ee.examples.entitybooks.ejb.BookRemoteHome</home>
<remote>corej2ee.examples.entitybooks.ejb.BookRemote</remote>
<local-home> corej2ee.examples.entitybooks.ejb.BookLocalHome
</local-home>
<local> corej2ee.examples.entitybooks.ejb. BookLocal</local>
<ejb-class>corej2ee.examples.entitybooks.ejb.BookEJB</ejb-class>
v041102
Entity Beans
45
Define the Primary Key Class
Enterprise
Java
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
v041102
Entity Beans
46
Define the Container Managed
Fields (CMP)
Enterprise
Java
<abstract-schema-name>Book</abstract-schema-name>
<cmp-field>
<field-name>author</field-name>
</cmp-field>
<cmp-field>
<field-name>id</field-name>
</cmp-field>
<cmp-field>
<field-name>title</field-name>
</cmp-field>
<cmp-field>
<field-name>topic</field-name>
</cmp-field>
<primkey-field>id</primkey-field>
v041102
Entity Beans
47
Define Environment Properties
Enterprise
Java
<!-- env-entry - lists properties that will be placed in the
bean's environment at run-time.
-->
<env-entry>
<description>This is a sample env entry.</description>
<env-entry-name>example</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Sample Environment Value</env-entry-value>
</env-entry>
v041102
Entity Beans
48
Define EJB References
Enterprise
Java
<ejb-ref>
<ejb-ref-name></ejb-ref-name>
<ejb-ref-type>Session or Entity</ejb-ref-type>
<home></home>
<remote></remote>
<ejb-link></ejb-link>
</ejb-ref>
<ejb-local-ref>
<ejb-ref-name></ejb-ref-name>
<ejb-ref-type>Session or Entity</ejb-ref-type>
<local-home></local-home>
<local></local>
<ejb-link></ejb-link>
</ejb-local-ref>
v041102
Entity Beans
49
Define Queries CMP Queries
Enterprise
Java
<query>
<query-method>
<method-name>findAll</method-name>
<!— declared in BookLocal/RemoteHome
<method-params>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(b) FROM Book b</ejb-ql>
</query>
v041102
Entity Beans
50
Define Client Jar File
Enterprise
Java
<!-- ejb-client-jar
Specifies the jar file that contains classes for use by remote
clients of the component.
-->
<ejb-client-jar>entityBooksEJBClient.jar </ejb-client-jar>
</ejb-jar>
v041102
Entity Beans
51
Things We Skipped (coming…)
Enterprise
Java
• Defining Security Roles
• Defining Security Access
• Defining Transaction Scope
v041102
Entity Beans
52
Defining Database-Specific Mapping
(weblogic-cmp-rdbms-jar.xml)
Enterprise
Java
<!DOCTYPE weblogic-rdbms-jar PUBLIC
'-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS Persistence//EN’
'http://www.bea.com/servers/wls700/dtd/weblogic-rdbms20-persistence-700.dtd'>
<weblogic-rdbms-jar>
<weblogic-rdbms-bean>
<ejb-name>BookCMP</ejb-name>
<data-source-name>corej2ee/jdbc/DS</data-source-name>
<table-map>
<table-name>entityBooks_Book</table-name>
...
<field-map>
</field-map>
</table-map>
</weblogic-rdbms-bean>
<create-default-dbms-tables>True</create-default-dbms-tables>
</weblogic-rdbms-jar>
v041102
Entity Beans
53
Map Columns to Fields
(weblogic-cmp-rdbms-jar.xml)
<field-map>
<cmp-field>author</cmp-field>
<dbms-column>author</dbms-column>
</field-map>
<field-map>
<cmp-field>id</cmp-field>
<dbms-column>id</dbms-column>
</field-map>
<field-map>
<cmp-field>title</cmp-field>
<dbms-column>title</dbms-column>
</field-map>
<field-map>
<cmp-field>topic</cmp-field>
<dbms-column>topic</dbms-column>
</field-map>
v041102
Entity Beans
Enterprise
Java
54
Map Container-Specific Resources
(weblogic-ejb-jar.xml)
Enterprise
Java
<!DOCTYPE weblogic-ejb-jar PUBLIC
"-//BEA Systems, Inc.//DTD WebLogic 7.0.0 EJB//EN”
"http://www.bea.com/servers/wls700/dtd/weblogic-ejb-jar.dtd" >
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>BookCMP</ejb-name>
<entity-descriptor>
...
</entity-descriptor>
<local-jndi-name>corej2ee/examples/entitybooks/BookCMPLocalHome
</local-jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
v041102
Entity Beans
55
Map Container-Specific Resources
(weblogic-ejb-jar.xml)
Enterprise
Java
<entity-descriptor>
<persistence>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>6.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-use>
</persistence>
</entity-descriptor>
v041102
Entity Beans
56
JBoss (jbosscmp-jdbc.xml)
Enterprise
Java
<jbosscmp-jdbc>
<defaults>
<datasource>java:coredev/jdbc/DS</datasource>
<datasource-mapping>Hypersonic SQL</datasource-mapping>
<create-table>true</create-table>
<remove-table>true</remove-table>
</defaults>
<enterprise-beans>
<entity>
<ejb-name>BookCMP</ejb-name>
<table-name>entityBooks_Book</table-name>
<cmp-field>
<field-name>id</field-name>
<column-name>id</column-name>
</cmp-field>
<cmp-field>
<field-name>title</field-name>
<column-name>title</column-name>
</cmp-field>
<cmp-field>
<field-name>topic</field-name>
<column-name>topic</column-name>
</cmp-field>
</entity>
</enterprise-beans>
</jbosscmp-jdbc>
v041102
Entity Beans
57
Database Synchronization
Enterprise
Java
• 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
v041102
Entity Beans
58
State Management
Enterprise
Java
• State synchronization methods
– ejbLoad
– ejbStore
• Resource Management methods
– ejbActivate
– ejbPassivate
v041102
Entity Beans
59
Entity Bean Types
Enterprise
Java
• 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
v041102
Entity Beans
60
CMP Summary
Enterprise
Java
• Eliminates a lot of code
– less code means fewer bugs
• Provides support for relationships (covered later)
• Provides support for database-generic queries
(EJB-QL covered later)
• Problems
– abstract model based on Java; database
implementations do not always map Java constructs the
same
v041102
Entity Beans
61
Enterprise
Java
Bean Managed Persistence
BMP
v041102
Entity Beans
62
Bean Managed Persistence (BMP)
Enterprise
Java
• The BookBMPBean uses BMP
– implemented all database interaction
– create, remove, and find
• Have to do object-relational mapping
• Synchronize bean state with database when
requested by container
v041102
Entity Beans
63
Activation and Passivation
Enterprise
Java
• 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
v041102
Entity Beans
64
BMP Summary
Enterprise
Java
• 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
v041102
Entity Beans
65
Implement a BMP Entity Bean
Enterprise
Java
package corej2ee.examples.entitybooks.ejb;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
…
public class BookBMP extends BookEJB {
private DataSource dataSource_;
private EntityContext ctx_;
v041102
Entity Beans
66
Implement the Abstract Data Model
Enterprise
Java
private String id_;
private String title_;
private String author_;
private String topic_;
public void setId(String id)
{ id_ = id; }
public String getId()
{ return id_; }
public void setAuthor(String author)
{ author_ = author; }
public String getAuthor()
{ return author_; }
public void setTitle(String title)
{ title_ = title; }
public String getTitle()
{ return title_; }
public void setTopic(String topic)
{ topic_ = topic; }
public String getTopic()
{ return topic_; }
v041102
Entity Beans
67
Locate the Database
public void setEntityContext(EntityContext ctx) {
super.setEntityContext(ctx);
ctx_ = ctx;
InitialContext jndi = null;
try {
jndi = new InitialContext();
dataSource_ = (DataSource)jndi.lookup("java:comp/env/jdbc/mydb");
}
catch (NamingException ex) {
throw new EJBException(ex);
}
finally {
try { if (jndi!=null) jndi.close(); } catch (Exception e) {}
}
v041102
Entity Beans
}
Enterprise
Java
68
Implement DB Insertion
Enterprise
Java
public String ejbCreate(String id, String title, String author, String topic) {
super.ejbCreate(id, title, author, topic);
Connection conn = null;
PreparedStatement pstatement = null;
try {
conn = dataSource_.getConnection();
pstatement=conn.prepareStatement("insert into Book (id, title, author, topic)"+
” values (?, ?, ?, ?)");
pstatement.setString(1,id_);
pstatement.setString(2,title_);
pstatement.setString(3,author_); pstatement.setString(4,topic_);
pstatement.execute();
return id_;
}
catch(SQLException ex) { throw new EJBException(ex); }
finally { … }
}
v041102
Entity Beans
69
Implement PostCreate
Enterprise
Java
public void ejbPostCreate(
String id, String title, String author, String topic) {
super.ejbPostCreate(id, title, author, topic);
}
v041102
Entity Beans
70
Implement DB Load
Enterprise
Java
public void ejbLoad() {
Connection conn = null;
PreparedStatement pstatement = null;
ResultSet rs = null;
try {
conn = dataSource_.getConnection();
pstatement = conn.prepareStatement(
"select id, title, author, topic from Book " + "where id = ?");
pstatement.setString(1, (String)ctx_.getPrimaryKey());
rs = pstatement.executeQuery();
if (rs.next()) {
...
v041102
Entity Beans
71
Implement DB Load (cont.)
Enterprise
Java
if (rs.next()) {
id_ = rs.getString("id");
title_ = rs.getString("title");
author_ = rs.getString("author");
topic_ = rs.getString("topic");
super.ejbLoad();
}
else {
throw new EJBException("unable to locate row");
}
}
catch(SQLException ex) {
throw new EJBException(getText(ex));
}
finally { … }
v041102
Entity Beans
72
Implement DB Store
Enterprise
Java
public void ejbStore() {
Connection conn = null; PreparedStatement pstatement = null;
try {
super.ejbStore();
conn = dataSource_.getConnection();
pstatement = conn.prepareStatement(
"update Book set title=?, author=?, topic=? " + "where id = ?");
pstatement.setString(1,title_); pstatement.setString(2,author_);
pstatement.setString(3,topic_); pstatement.setString(4,id_);
pstatement.executeUpdate();
}
catch(SQLException ex) { throw new EJBException(getText(ex)); }
finally { … }
}
v041102
Entity Beans
73
Implement DB Remove
Enterprise
Java
public void ejbRemove() {
Connection conn = null;
PreparedStatement pstatement = null;
try {
super.ejbRemove();
conn = dataSource_.getConnection();
pstatement = conn.prepareStatement("delete from Book " + "where id = ?");
pstatement.setString(1, (String)ctx_.getPrimaryKey());
pstatement.executeUpdate();
}
catch(SQLException ex) { throw new EJBException(getText(ex)); }
finally { … }
}
v041102
Entity Beans
74
Implement Finders
Enterprise
Java
public String ejbFindByPrimaryKey(String pk) throws FinderException {
Connection conn = null;
PreparedStatement pstatement = null;
ResultSet rs = null;
try {
conn = dataSource_.getConnection();
pstatement = conn.prepareStatement("select id from Book " + "where id = ?");
pstatement.setString(1, pk);
rs = pstatement.executeQuery();
if (rs.next()) { return rs.getString("id"); }
else { throw new ObjectNotFoundException(pk + " no found"); }
}
catch(SQLException ex) { throw new EJBException(getText(ex)); }
finally {... }
}
v041102
Entity Beans
75
Implement Finders (cont.)
public Collection ejbFindAll() throws FinderException {
Connection conn = null;
PreparedStatement pstatement = null;
ResultSet rs = null;
try {
Vector pKeys = new Vector();
conn = dataSource_.getConnection();
pstatement = conn.prepareStatement("select id from Book ");
rs = pstatement.executeQuery();
while (rs.next()) {
pKeys.add(rs.getString("id")); }
return pKeys;
}
catch(SQLException ex) {throw new EJBException(getText(ex)); }
finally {... }
v041102
Entity Beans
}
Enterprise
Java
76
Configure Deployment Descriptors
(ejb-jar.xml)
Enterprise
Java
<entity>
<ejb-name>BookBMP</ejb-name>
<local-home>corej2ee.examples.entitybooks.ejb.BookLocalHome</local-home>
<local>corej2ee.examples.entitybooks.ejb.BookLocal</local>
<ejb-class>corej2ee.examples.entitybooks.ejb.BookBMP</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<resource-ref>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</entity>
v041102
Entity Beans
77
Configure Deployment Descriptors
(weblogic-ejb-jar.xml)
Enterprise
Java
<weblogic-enterprise-bean>
<ejb-name>BookBMP</ejb-name>
<reference-descriptor>
<resource-description>
<res-ref-name>jdbc/mydb</res-ref-name>
<jndi-name>corej2ee/jdbc/DS</jndi-name>
</resource-description>
</reference-descriptor>
<local-jndi-name>corej2ee/examples/entitybooks/BookBMPLocalHome
</local-jndi-name>
</weblogic-enterprise-bean>
v041102
Entity Beans
78
jboss.xml
Enterprise
Java
<entity>
<ejb-name>BookBMP</ejb-name>
<local-jndi-name>
corej2ee/examples/entitybooks/BookBMPLocalHome
</local-jndi-name>
<resource-ref>
<res-ref-name>jdbc/mydb</res-ref-name>
<jndi-name>java:coredev/jdbc/DS</jndi-name>
</resource-ref>
</entity>
v041102
Entity Beans
79
Enterprise
Java
Entity Bean Performance Issues
v041102
Entity Beans
80
Performance Issues
Enterprise
Java
• When could Entity Beans be expensive
– CMP performs eager database synchronization on each
transaction (EJB 2.0 abstract schema much better)
– BMP allows for lazy database synchronization
• Who should call the Entity Bean’s Remote
methods ?
• 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
v041102
Entity Beans
81
Entity Bean Summary
•
•
•
•
Enterprise
Java
Models persistent state in database
Facilitates declarative persistence
BMP vs. CMP
Performance implications
– wrap calls to entity beans with session beans
v041102
Entity Beans
82