Title: Container and Bean Managed Persistence
1Entity Beans
- Container and Bean Managed Persistence
2Topics
- Understanding Entity Beans
- Implementing Entity Beans
- Container Managed Persistence
- Bean Managed Persistence
3Understanding Entity Beans
4Enterprise Bean
- 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
5Bean Types
- 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
6Bean Types
- Message Beans
- Stateless component invoked using asynchronous
message (JMS)
7Container and Beans
create find
JVM
Container
Remote Home
Remote Home Stub
Remote Client
Remote Object
Remote Object Stub
EJB Class
EJB Class
EJB Class
Local Home
Bean Pool
deposit transfer
Local Client
Local Object
8Entity Bean (from 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
9Entity Bean Support
- 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)
- Annotations for persistence mappings
- No home or component interface
- Hibernate-inspired
- Not an abstract class
10Entity Bean Lifecycle
11Entity Bean States
- 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
12Entity Bean Transitions
- Does Not Exist -gt 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 EJBs reference to container (ctx)
13Entity Bean Transitions
- Pooled -gt Ready (via creation)
- occurs when client invokes a Home.create(ltargsgt)
- object created, bean instance located
- methods invoked
- ejbCreate(ltargsgt)
- may establish properties
- must establish primary key
- object not yet ready to be advertised
- ejbPostCreate(ltargsgt)
- establish relationships (object ready to be
advertised)
14Entity Bean Transitions
- Pooled -gt Ready (via query)
- occurs when Home.find (ltargs) or
this.ejbSelect(ltargsgt) 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
15Entity Bean Transitions
- Ready -gt 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
16Entity Bean Transitions
- Ready -gt 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
17Entity Bean Transitions
- Ready State
- occurs when client invokes object.ltbusiness
methodgt() - 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
18Implementing CMP Entity Beans
19Creating a Book CMP Entity Bean
- (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
20Entity Bean Class
container.BookEJB_Impl ltabstract method
implsgt ltconcrete method interposegt
21EJBContext
22PrimaryKey Class
- 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
23PrimaryKey Classes
- 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
24Create the PrimaryKey Class
- 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
-
25Value Objects
- 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
26Create Book Value Objects
- 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 - ...
27Object Interface
- Defines the business methods to be implemented by
the Bean that can be invoked by a client - Arguments and return types must be legal RMI-IIOP
types - Local Interface
- fine-grain access from Session Façade
- Remote Interface
- larger-grain bulk accessors
28Local Object Interface
- 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)
-
29Remote Object Interface
- 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 -
30Home Interface
- createltSuffixgt() and createltSuffixgt( args )
- creates row in database
- optional with entity beans
- must have matching ejbCreateltSuffixgt() and
ejbPostCreateltSuffixgt() methods in bean
implementation if present - find()
- findByPrimaryKey(ltprimary key classgt) 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 - lthome methodsgt() - work on table as a whole
31Create Local Home Interface
- 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
32Local Creation Example
- InitialContext jndi new InitialContext()
- BookLocalHome bHome (BookLocalHome)jndi.lookup("
javacomp/env/ejb/BookLocalHome") - BookLocal bookLocal bHome.create(
- book.getId(), book.getTitle(),
book.getAuthor(), book.getTopic())
33Create Remote Home Interface
- 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
34Remote Creation Example
- InitialContext jndi new InitialContext()
- BookRemoteHome bHome (BookRemoteHome)
- PortableObjectRemote.narrow(jndi.lookup("java
comp/env/ejb/BookRemoteHome"), - BookRemoteHome.class)
- BookRemote bookRemote bHome.create(book)
35Create the Bean Class
- 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_
-
36Define the Abstract Accessors
- 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()
37Implement the Bean Class Business Methods
- public Book getValues()
- return new Book(getId(), getTitle(),
getAuthor(), getTopic()) -
- public void setValues(Book values)
- setTitle(values.getTitle())
- setAuthor(values.getAuthor())
- setTopic(values.getTopic())
-
38Coordinate Access to Container
- / 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
39Implement Bean ClassCreate Methods
- /
- 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)
40Implement Bean ClassCreate Methods (cont.)
- 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) -
41Implement Bean ClassRemove Method
- /
- 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())
42Implement Bean ClassResource Management Methods
- / 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()
43Implement Bean ClassDatabase Synchronization
Methods
- /
- 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()
44Create Deployment Descriptor(ejb-jar.xml)
- lt!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems,
Inc.//DTD Enterprise JavaBeans 2.0//EN'
'http//java.sun.com/dtd/ejb-jar_2_0.dtd'gt - ltejb-jargt
- ltenterprise-beansgt
- ltentitygt
- ltejb-namegtBookCMPlt/ejb-namegt
- ...
- lt/entitygt
- lt/enterprise-beansgt
- ltassembly-descriptorgt
- ltcontainer-transactiongt
- ...
- lt/container-transactiongt
- lt/ejb-jargt
45Define the Individual Beans
- ltentitygt
- ltejb-namegtBookCMPlt/ejb-namegt
- lthomegtcorej2ee.examples.entitybooks.ejb.Book
RemoteHomelt/homegt - ltremotegtcorej2ee.examples.entitybooks.ejb.Bo
okRemotelt/remotegt - ltlocal-homegt corej2ee.examples.entitybooks.e
jb.BookLocalHomelt/local-homegt - ltlocalgt corej2ee.examples.entitybooks.ejb.
BookLocallt/localgt - ltejb-classgtcorej2ee.examples.entitybooks.ejb
.BookEJBlt/ejb-classgt -
46Define the Primary Key Class
- ltpersistence-typegtContainerlt/persistence-typ
egt - ltprim-key-classgtjava.lang.Stringlt/prim-key-c
lassgt - ltreentrantgtFalselt/reentrantgt
47Define the Container ManagedFields (CMP)
- ltabstract-schema-namegtBooklt/abstract-schema-namegt
- ltcmp-fieldgt
- ltfield-namegtauthorlt/field-namegt
- lt/cmp-fieldgt
- ltcmp-fieldgt
- ltfield-namegtidlt/field-namegt
- lt/cmp-fieldgt
- ltcmp-fieldgt
- ltfield-namegttitlelt/field-namegt
- lt/cmp-fieldgt
- ltcmp-fieldgt
- ltfield-namegttopiclt/field-namegt
- lt/cmp-fieldgt
- ltprimkey-fieldgtidlt/primkey-fieldgt
48Define Environment Properties
- lt!-- env-entry - lists properties that will be
placed in the - bean's environment at run-time.
- --gt
- ltenv-entrygt
- ltdescriptiongtThis is a sample env
entry.lt/descriptiongt - ltenv-entry-namegtexamplelt/env-entry-namegt
- ltenv-entry-typegtjava.lang.Stringlt/env-entry-t
ypegt - ltenv-entry-valuegtSample Environment
Valuelt/env-entry-valuegt - lt/env-entrygt
49Define EJB References
- ltejb-refgt
- ltejb-ref-namegtlt/ejb-ref-namegt
- ltejb-ref-typegtSession or
Entitylt/ejb-ref-typegt - lthomegtlt/homegt
- ltremotegtlt/remotegt
- ltejb-linkgtlt/ejb-linkgt
- lt/ejb-refgt
- ltejb-local-refgt
- ltejb-ref-namegtlt/ejb-ref-namegt
- ltejb-ref-typegtSession or
Entitylt/ejb-ref-typegt - ltlocal-homegtlt/local-homegt
- ltlocalgtlt/localgt
- ltejb-linkgtlt/ejb-linkgt
- lt/ejb-local-refgt
50Define Queries CMP Queries
- ltquerygt
- ltquery-methodgt
- ltmethod-namegtfindAlllt/method-namegt
- lt! declared in BookLocal/RemoteHome?
- ltmethod-paramsgt
- lt/method-paramsgt
- lt/query-methodgt
- ltejb-qlgtSELECT OBJECT(b) FROM Book blt/ejb-qlgt
- lt/querygt
51Define Client Jar File
- lt!-- ejb-client-jar
- Specifies the jar file that contains
classes for use by remote - clients of the component.
- --gt
- ltejb-client-jargtentityBooksEJBClient.jar
lt/ejb-client-jargt - lt/ejb-jargt
52Things We Skipped (coming)
- Defining Security Roles
- Defining Security Access
- Defining Transaction Scope
53Defining Database-Specific Mapping(weblogic-cmp-r
dbms-jar.xml)
- lt!DOCTYPE weblogic-rdbms-jar PUBLIC '-//BEA
Systems, Inc.//DTD WebLogic 7.0.0 EJB RDBMS
Persistence//EN'http//www.bea.com/servers/wls70
0/dtd/weblogic-rdbms20-persistence-700.dtd'gt - ltweblogic-rdbms-jargt
- ltweblogic-rdbms-beangt
- ltejb-namegtBookCMPlt/ejb-namegt
- ltdata-source-namegtcorej2ee/jdbc/DSlt/data-sourc
e-namegt - lttable-mapgt
- lttable-namegtentityBooks_Booklt/table-namegt
- . . .
- ltfield-mapgt
- lt/field-mapgt
- lt/table-mapgt
- lt/weblogic-rdbms-beangt
- ltcreate-default-dbms-tablesgtTruelt/create-default
-dbms-tablesgt - lt/weblogic-rdbms-jargt
54Map Columns to Fields(weblogic-cmp-rdbms-jar.xml)
- ltfield-mapgt
- ltcmp-fieldgtauthorlt/cmp-fieldgt
- ltdbms-columngtauthorlt/dbms-columngt
- lt/field-mapgt
- ltfield-mapgt
- ltcmp-fieldgtidlt/cmp-fieldgt
- ltdbms-columngtidlt/dbms-columngt
- lt/field-mapgt
- ltfield-mapgt
- ltcmp-fieldgttitlelt/cmp-fieldgt
- ltdbms-columngttitlelt/dbms-columngt
- lt/field-mapgt
- ltfield-mapgt
- ltcmp-fieldgttopiclt/cmp-fieldgt
- ltdbms-columngttopiclt/dbms-columngt
- lt/field-mapgt
-
55Map Container-Specific Resources(weblogic-ejb-jar
.xml)
- lt!DOCTYPE weblogic-ejb-jar PUBLIC"-//BEA
Systems, Inc.//DTD WebLogic 7.0.0
EJB//EN"http//www.bea.com/servers/wls700/dtd/we
blogic-ejb-jar.dtd" gt - ltweblogic-ejb-jargt
- ltweblogic-enterprise-beangt
- ltejb-namegtBookCMPlt/ejb-namegt
- ltentity-descriptorgt
- ...
- lt/entity-descriptorgt
- ltlocal-jndi-namegtcorej2ee/examples/entitybooks
/BookCMPLocalHome - lt/local-jndi-namegt
- lt/weblogic-enterprise-beangt
- lt/weblogic-ejb-jargt
56Map Container-Specific Resources(weblogic-ejb-jar
.xml)
- ltentity-descriptorgt
- ltpersistencegt
- ltpersistence-usegt
- lttype-identifiergtWebLogic_CMP_RDBMSlt/typ
e-identifiergt - lttype-versiongt6.0lt/type-versiongt
- lttype-storagegtMETA-INF/weblogic-cmp-rdbm
s-jar.xmllt/type-storagegt - lt/persistence-usegt
- lt/persistencegt
- lt/entity-descriptorgt
57JBoss (jbosscmp-jdbc.xml)
ltjbosscmp-jdbcgt ltdefaultsgt
ltdatasourcegtjavacoredev/jdbc/DSlt/datasourcegt
ltdatasource-mappinggtHypersonic
SQLlt/datasource-mappinggt ltcreate-tablegttruelt
/create-tablegt ltremove-tablegttruelt/remove-ta
blegt lt/defaultsgt ltenterprise-beansgt
ltentitygt ltejb-namegtBookCMPlt/ejb-namegt
lttable-namegtentityBooks_Booklt/table-namegt
ltcmp-fieldgt ltfield-namegtidlt/fie
ld-namegt ltcolumn-namegtidlt/column-namegt
lt/cmp-fieldgt ltcmp-fieldgt
ltfield-namegttitlelt/field-namegt
ltcolumn-namegttitlelt/column-namegt
lt/cmp-fieldgt ltcmp-fieldgt
ltfield-namegttopiclt/field-namegt
ltcolumn-namegttopiclt/column-namegt
lt/cmp-fieldgt lt/entitygt
lt/enterprise-beansgt lt/jbosscmp-jdbcgt
58Database 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
59State Management
- State synchronization methods
- ejbLoad
- ejbStore
- Resource Management methods
- ejbActivate
- ejbPassivate
60Entity 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
61CMP Summary
- 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
62Bean Managed Persistence
63Bean Managed Persistence (BMP)
- 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
64Activation 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
65BMP 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
66Implement a BMP Entity Bean
- package corej2ee.examples.entitybooks.ejb
- import javax.ejb.EntityBean
- import javax.ejb.EntityContext
-
- public class BookBMP extends BookEJB
- private DataSource dataSource_
- private EntityContext ctx_
67Implement the Abstract Data Model
- 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_
68Locate 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) -
-
69Implement DB Insertion
- 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()
- pstatementconn.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
-
70Implement PostCreate
- public void ejbPostCreate(
- String id, String title, String author, String
topic) - super.ejbPostCreate(id, title, author, topic)
-
71Implement DB Load
- 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_.getPrim
aryKey()) - rs pstatement.executeQuery()
- if (rs.next())
- ...
72Implement DB Load (cont.)
- 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
73Implement DB Store
- 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
-
74Implement DB Remove
- 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_.getPrim
aryKey()) - pstatement.executeUpdate()
-
- catch(SQLException ex) throw new
EJBException(getText(ex)) - finally
-
75Implement Finders
- 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 ...
-
76Implement 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 ...
-
77Configure Deployment Descriptors(ejb-jar.xml)
- ltentitygt
- ltejb-namegtBookBMPlt/ejb-namegt
- ltlocal-homegtcorej2ee.examples.entitybooks.ejb
.BookLocalHomelt/local-homegt - ltlocalgtcorej2ee.examples.entitybooks.ejb.Book
Locallt/localgt - ltejb-classgtcorej2ee.examples.entitybooks.ejb.
BookBMPlt/ejb-classgt - ltpersistence-typegtBeanlt/persistence-typegt
- ltprim-key-classgtjava.lang.Stringlt/prim-key-cl
assgt - ltreentrantgtFalselt/reentrantgt
- ltresource-refgt
- ltres-ref-namegtjdbc/mydblt/res-ref-namegt
- ltres-typegtjavax.sql.DataSourcelt/res-typegt
- ltres-authgtContainerlt/res-authgt
- lt/resource-refgt
- lt/entitygt
78Configure Deployment Descriptors(weblogic-ejb-jar
.xml)
- ltweblogic-enterprise-beangt
- ltejb-namegtBookBMPlt/ejb-namegt
- ltreference-descriptorgt
- ltresource-descriptiongt
- ltres-ref-namegtjdbc/mydblt/res-ref-namegt
- ltjndi-namegtcorej2ee/jdbc/DSlt/jndi-namegt
- lt/resource-descriptiongt
- lt/reference-descriptorgt
- ltlocal-jndi-namegtcorej2ee/examples/entitybooks
/BookBMPLocalHome - lt/local-jndi-namegt
- lt/weblogic-enterprise-beangt
79jboss.xml
ltentitygt ltejb-namegtBookBMPlt/ejb-namegt
ltlocal-jndi-namegt corej2ee/examples/entity
books/BookBMPLocalHome lt/local-jndi-namegt
ltresource-refgt ltres-ref-namegtjdbc/mydblt/r
es-ref-namegt ltjndi-namegtjavacoredev/jdbc/
DSlt/jndi-namegt lt/resource-refgt lt/entitygt
80Entity Bean Performance Issues
81Performance Issues
- 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 Beans 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
82Entity Bean Summary
- Models persistent state in database
- Facilitates declarative persistence
- BMP vs. CMP
- Performance implications
- wrap calls to entity beans with session beans