Entity Beans: Container and Bean Managed Persistence
Entity Beans: Container and Bean Managed Persistence
Entity Beans
Container and Bean Managed Persistence
v020402
Entity Beans
Topics
Understanding Entity Beans Implementing Entity Beans
Container Managed Persistence Bean Managed Persistence
Enterprise Java
v020402
Entity Beans
Enterprise Java
v020402
Entity Beans
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
v020402
Entity Beans
Bean Types
Entity Beans
Represents persistent data in a database
Account and deposit()
Enterprise Java
Session Beans
Represents business logic operations
Teller and transfer()
Bean Types
Message Beans
Stateless component invoked using asynchronous message (JMS)
Enterprise Java
v020402
Entity Beans
Enterprise Java
deposit transfer
v020402
Entity Beans
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
v020402
Entity Beans
Enterprise Java
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
v020402 Entity Beans 9
Enterprise Java
this.ejbSelect() Home.f ind()/ejbFind() Home.XXX()/ejbHomeXXX() Home.c reate()/ejbCreate(); ejbPostCreate() Ready activate object()/ejbActivateObject
object.remove()/ejbRemove()
this.ejbSelect()
v020402
Entity Beans
10
Enterprise Java
Pooled
state entered when container offers component state re-entered when object disassociated from bean
Ready
state where business methods can be invoked
v020402
Entity Beans
11
Enterprise Java
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)
v020402
Entity Beans
12
Enterprise Java
v020402
Entity Beans
13
Enterprise Java
v020402
Entity Beans
14
Enterprise Java
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
v020402
Entity Beans
15
Enterprise Java
called prior to database removal in CMP called to remove from database in BMP
v020402
Entity Beans
16
Enterprise Java
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
v020402 Entity Beans 17
Enterprise Java
v020402
Entity Beans
18
Enterprise Java
Create the Local/Remote Home Interface Create the Bean Class Create the Deployment Descriptors
v020402 Entity Beans 19
...ejb.enti ty.bean.BookEJB
java.lang.String -ctx_:EntityContext -PRINT_DEBUG:boolean +ejbActivate:v oid +ejbPassivate:void +ejbLoad:void +ejbStore:void +ejbRemove:void +setEntity Context:void +unsetEntityContext:void #log:void id:String author:String title:String topic:String
Enterprise Java
v020402
Entity Beans
20
EJBContext
interf ace j avax.ej b.EJBContext +getCallerIdentity:java.security.Identity +getCallerPrincipal:java.security.Principal +getEJBHome:javax.ejb.EJBHome +getEnvironment:java.util.Properties +getRollb ackOnly:boolean +getUserTransaction:javax.transaction.UserTransaction +isCallerInRole:b oolean +isCallerInRole:b oolean +setRollb ackOnly:void callerIdentity:java.security.Identity callerPrinc ipal:jav a.security.Principal EJBHome:javax.ejb.EJBHome environment:java.util.Properties rollbackOnly:boolean userTrans action:javax.transaction.UserTransaction
Enterprise Java
+getEJBObject:javax.ejb.EJBObject EJBObject:javax.ejb.EJBObjec t
v020402
Entity Beans
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
v020402 Entity Beans 22
PrimaryKey Classes
key values
Enterprise Java
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
v020402
Entity Beans
23
Enterprise Java
24
Value 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 Faade Remote
Enterprise Java
v020402
Entity Beans
25
Enterprise Java
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 Faade
Remote Interface
larger-grain bulk accessors
v020402
Entity Beans
27
Enterprise Java
28
Enterprise Java
v020402
Entity Beans
29
Home Interface
create<Suffix>() and create<Suffix>( args )
Enterprise Java
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
Enterprise Java
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; }
v020402 Entity Beans 31
Enterprise Java
v020402
Entity Beans
32
Enterprise Java
33
Enterprise Java
v020402
Entity Beans
34
Enterprise Java
v020402
Entity Beans
35
Enterprise Java
36
Enterprise Java
v020402
Entity Beans
37
Enterprise Java
38
Enterprise Java
/** This method is where we establish any relationships to our object. */ public void ejbPostCreate(String id) {}
v020402
Entity Beans
39
Enterprise Java
public String ejbCreate(String id, String title, String author, String topic) { 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) { }
v020402
Entity Beans
40
Enterprise Java
v020402
Entity Beans
41
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() { }
v020402 Entity Beans 42
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() { }
v020402
Entity Beans
43
Enterprise Java
44
Enterprise Java
v020402
Entity Beans
45
Enterprise Java
v020402
Entity Beans
46
Enterprise Java
47
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>
v020402
Entity Beans
48
Enterprise Java
49
Enterprise Java
v020402
Entity Beans
50
Enterprise Java
v020402
Entity Beans
51
Enterprise Java
v020402
Entity Beans
52
Enterprise Java
53
Enterprise Java
v020402
Entity Beans
54
Enterprise Java
<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB//EN' 'http://www.bea.com/servers/wls600/dtd/weblogic-ejb-jar.dtd'>
55
Enterprise Java
<entity-descriptor> <persistence> <persistence-type> <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-type> <persistence-use> <type-identifier>WebLogic_CMP_RDBMS</type-identifier> <type-version>6.0</type-version> </persistence-use> </persistence> </entity-descriptor>
v020402 Entity Beans 56
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
v020402
Entity Beans
57
State Management
State synchronization methods
ejbLoad ejbStore
Enterprise Java
v020402
Entity Beans
58
Enterprise Java
v020402
Entity Beans
59
CMP Summary
Eliminates a lot of code
less code means fewer bugs
Enterprise Java
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 many containers can only map a bean to one table
v020402 Entity Beans 60
Enterprise Java
v020402
Entity Beans
61
Enterprise Java
Have to do object-relational mapping Synchronize bean state with database when requested by container
v020402
Entity Beans
62
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
v020402
Entity Beans
63
BMP Summary
Have to handle all database interaction
except transactions
Enterprise Java
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
v020402
Entity Beans
64
Enterprise Java
public class BookBMP extends BookEJB { private DataSource dataSource_; private EntityContext ctx_;
v020402
Entity Beans
65
Enterprise Java
66
Enterprise Java
67
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 { } }
v020402 Entity Beans 68
Implement PostCreate
public void ejbPostCreate( String id, String title, String author, String topic) { super.ejbPostCreate(id, title, author, topic); }
Enterprise Java
v020402
Entity Beans
69
Implement 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_.getPrimaryKey()); rs = pstatement.executeQuery(); if (rs.next()) { ...
Enterprise Java
v020402
Entity Beans
70
Enterprise Java
71
Implement 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 { } }
v020402 Entity Beans
Enterprise Java
72
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 { } }
v020402 Entity Beans 73
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 {... } }
v020402 Entity Beans 74
Enterprise Java
75
Enterprise Java
<entity> <ejb-name>BookBMP</ejb-name> <local-home>ejava.examples.ejb.entity.bean.BookLocalHome</local-home> <local>ejava.examples.ejb.entity.bean.BookLocal</local> <ejb-class>ejava.examples.ejb.entity.bean.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>
v020402 Entity Beans 76
Enterprise Java
<weblogic-enterprise-bean> <ejb-name>BookBMP</ejb-name> <reference-descriptor> <resource-description> <res-ref-name>jdbc/mydb</res-ref-name> <jndi-name>ejava.jdbc.txDataSource</jndi-name> </resource-description> </reference-descriptor> <local-jndi-name>ejava/examples/ejb/entity/BMPBookLocalHome</local-jndiname> </weblogic-enterprise-bean>
v020402
Entity Beans
77
Enterprise Java
v020402
Entity Beans
78
Performance Issues
When could Entity Beans be expensive
Enterprise Java
CMP performs eager database synchronization on each transaction 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 Beans v020402 Entity 79
Enterprise Java
v020402
Entity Beans
80