0% found this document useful (0 votes)
60 views80 pages

Entity Beans: Container and Bean Managed Persistence

The document discusses entity beans in Enterprise Java, including container-managed and bean-managed persistence. It covers topics such as implementing entity beans, understanding their lifecycle and states, creating primary key classes, value objects, and local/remote interfaces.

Uploaded by

m_sdeepika9780
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views80 pages

Entity Beans: Container and Bean Managed Persistence

The document discusses entity beans in Enterprise Java, including container-managed and bean-managed persistence. It covers topics such as implementing entity beans, understanding their lifecycle and states, creating primary key classes, value objects, and local/remote interfaces.

Uploaded by

m_sdeepika9780
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 80

Enterprise Java

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

Understanding Entity Beans

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

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


v020402 Entity Beans 5

Bean Types
Message Beans
Stateless component invoked using asynchronous message (JMS)

Enterprise Java

v020402

Entity Beans

Container and Beans


create find Remote Home Stub Remote Client Remote Object Stub Remote Object Local Home Local Client Local Object JVM Container Remote Home

Enterprise Java

EJB Class EJB Class EJB Class Bean Pool

deposit transfer

v020402

Entity Beans

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

v020402

Entity Beans

Entity Bean Support


Optional in EJB 1.0 Required in EJB 1.1 Revised in EJB 2.0

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

Entity Bean Lifecycle


Does Not Exist unload bean ins tance()/unsetEntityContext(); f inalize() Pooled passivate object()/ejbPassivate

Enterprise Java

bean instance required/Class.new Instance(); setEntityContext()

this.ejbSelect() Home.f ind()/ejbFind() Home.XXX()/ejbHomeXXX() Home.c reate()/ejbCreate(); ejbPostCreate() Ready activate object()/ejbActivateObject

object.remove()/ejbRemove()

object.method()/ejbLoad(); business method(); ejbStore()

this.ejbSelect()

v020402

Entity Beans

10

Entity Bean States


Does Not Exist
no instance instantiated default state at container startup

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

Entity Bean Transitions


Does Not Exist -> Pooled
methods invoked

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

Entity Bean Transitions


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)

Enterprise Java

v020402

Entity Beans

13

Entity Bean Transitions


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

Enterprise Java

v020402

Entity Beans

14

Entity Bean Transitions


Ready -> Pooled (passivation)

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

Entity Bean Transitions


Ready -> Pooled (removal)
occurs when client invokes object.remove() bean returned to pool methods invoked

Enterprise Java

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

v020402

Entity Beans

16

Entity Bean Transitions


Ready State

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

Implementing CMP Entity Beans

v020402

Entity Beans

18

Creating a Book CMP Entity Bean


(Create the Primary Key Class)
if required

Enterprise Java

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
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

Entity Bean Class

Enterprise Java

container.BookEJB_Impl <abstract method impls> <concrete method interpose>

+ejbCreate:String +ejbPostCreate:void +ejbCreate:String +ejbPostCreate:void

v020402

+setId:void +getId:String +setAuthor:void +getAuthor:String +setTitle:void +getTitle:String +setTopic:void +getTopic:String

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

interf ace j avax.ej b.SessionContext

+getEJBObject:javax.ejb.EJBObject EJBObject:javax.ejb.EJBObjec t

interf ace j avax.ej b.EntityContext

+getEJBObject:javax.ejb.EJBObject +getPrimaryKey:java.lang.Objec t EJBObject:javax.ejb.EJBObjec t primaryKey:jav a.lang.Object

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

Create the PrimaryKey Class


package ejava.examples.personnel.ejb20; 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 (ClassCastException ex) { return false;} } }
v020402 Entity Beans

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

Create Book Value Objects


package ejava.examples.ejb.entity; 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; } ... }
v020402 Entity Beans

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

Local Object Interface


Must extend javax.ejb.EJBLocalObject Methods may not throw javax.ejb.RemoteException
package ejava.examples.ejb.entity.bean; 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); }
v020402 Entity Beans

Enterprise Java

28

Remote Object Interface


Must extend javax.ejb.EJBObject Methods throw java.rmi.RemoteException
package ejava.examples.ejb.entity.bean; import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface BookLocal extends EJBObject { Book getValues() throws RemoteException; void setValues(Book values) throws RemoteException; }

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

<home methods>() - work on table as a whole


v020402 Entity Beans 30

Create Local Home Interface


package ejava.examples.ejb.entity.bean; import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; import javax.ejb.FinderException; import java.util.Collection;

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

Local Creation Example


InitialContext jndi = new InitialContext(); BookLocalHome bHome =(BookLocalHome) jndi.lookup("java:comp/env/ejb/BookLocalHome");

Enterprise Java

BookLocal bookLocal = bHome.create( book.getId(), book.getTitle(), book.getAuthor(), book.getTopic());

v020402

Entity Beans

32

Create Remote Home Interface


package ejava.examples.ejb.entity.bean; 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; }
v020402 Entity Beans

Enterprise Java

33

Remote Creation Example


InitialContext jndi = new InitialContext(); BookRemoteHome bHome =(BookRemoteHome) jndi.lookup("java:comp/env/ejb/BookRemoteHome");

Enterprise Java

BookRemote bookRemote = bHome.create(book);

v020402

Entity Beans

34

Create the Bean Class


package ejava.examples.ejb.entity.bean; import javax.ejb.EntityBean; import javax.ejb.EntityContext; public abstract class BookEJB implements EntityBean { /** This is our reference into the container. */ private EntityContext ctx_; }

Enterprise Java

v020402

Entity Beans

35

Define 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();
v020402 Entity Beans

Enterprise Java

36

Implement 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()); }

Enterprise Java

Real business methods would be much more complicated

v020402

Entity Beans

37

Coordinate 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; }
v020402 Entity Beans

Enterprise Java

38

Implement Bean Class Create 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) { setId(id); return null; //container gets primary key another way }

Enterprise Java

/** This method is where we establish any relationships to our object. */ public void ejbPostCreate(String id) {}

v020402

Entity Beans

39

Implement Bean Class Create Methods (cont.)

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

Implement Bean Class Remove 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()); }

Enterprise Java

v020402

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() { }
v020402 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() { }

v020402

Entity Beans

43

Create Deployment Descriptor (ejb-jar.xml)


<!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>Book</ejb-name> ... </entity> </enterprise-beans> <assembly-descriptor> <container-transaction> ... </container-transaction> </ejb-jar>
v020402 Entity Beans

Enterprise Java

44

Define the Individual Beans

Enterprise Java

<entity> <ejb-name>Book</ejb-name> <home>ejava.examples.ejb.entity.bean.BookRemoteHome</home> <remote>ejava.examples.ejb.entity.bean.BookRemote</remote> <local-home>ejava.examples.ejb.entity.bean.BookLocalHome</localhome> <local>ejava.examples.ejb.entity.bean.BookLocal</local> <ejb-class>ejava.examples.ejb.entity.bean.BookEJB</ejb-class>

v020402

Entity Beans

45

Define the Primary Key Class


<persistence-type>Container</persistence-type> <prim-key-class>java.lang.String</prim-key-class> <reentrant>False</reentrant>

Enterprise Java

v020402

Entity Beans

46

Define the Container Managed Fields (CMP)


<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>
v020402 Entity Beans

Enterprise Java

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>

v020402

Entity Beans

48

Define EJB References


<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>
v020402 Entity Beans

Enterprise Java

49

Define Queries CMP Queries


<query> <query-method> <method-name>findAll</method-name> <method-params> </method-params> </query-method> <ejb-ql>SELECT OBJECT(b) FROM Book b</ejb-ql> </query>

Enterprise Java

v020402

Entity Beans

50

Define Client Jar File


<!-- ejb-client-jar Specifies the jar file that contains classes for use by remote clients of the component. --> <ejb-client-jar>BookClient.jar</ejb-client-jar> </ejb-jar>

Enterprise Java

v020402

Entity Beans

51

Things We Skipped (coming)


Defining Security Roles Defining Security Access Defining Transaction Scope

Enterprise Java

v020402

Entity Beans

52

Defining Database-Specific Mapping (weblogic-cmp-rdbms-jar.xml)


<!DOCTYPE weblogic-rdbms-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 6.0.0 EJB RDBMS Persistence//EN' 'http://www.bea.com/servers/wls600/dtd/weblogic-rdbms20-persistence600.dtd'> <weblogic-rdbms-jar> <weblogic-rdbms-bean> <ejb-name>Book</ejb-name> <data-source-name>ejava.jdbc.txDataSource</data-source-name> <table-name>Book</table-name> <field-map> ... </field-map> </weblogic-rdbms-bean> <create-default-dbms-tables>True</create-default-dbms-tables> </weblogic-rdbms-jar> v020402 Entity Beans

Enterprise Java

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>

Enterprise Java

v020402

Entity Beans

54

Map Container-Specific Resources (weblogic-ejb-jar.xml)


<weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>Book</ejb-name> <entity-descriptor> ... </entity-descriptor> <local-jndi-name>ejava/examples/ejb/entity/BookLocalHome</local-jndiname> </weblogic-enterprise-bean> </weblogic-ejb-jar>
v020402 Entity Beans

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

Map Container-Specific Resources (weblogic-ejb-jar.xml)

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

Resource Management methods


ejbActivate ejbPassivate

v020402

Entity Beans

58

Entity Bean Types


Bean can have total control over loading and storing from database
Bean Managed Persistence (BMP)

Enterprise Java

Container can take over this responsibility


Container Managed Persistence (CMP) Specialized Implementations
Toplink for relational databases CICS

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

Bean Managed Persistence


BMP

v020402

Entity Beans

61

Bean Managed Persistence (BMP)


The CustomerBean used BMP
implemented all database interaction create, remove, and find

Enterprise Java

Have to do object-relational mapping Synchronize bean state with database when requested by container

v020402

Entity Beans

62

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

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

Implement a BMP Entity Bean


package ejava.examples.ejb.entity.bean; import javax.ejb.EntityBean; import javax.ejb.EntityContext;

Enterprise Java

public class BookBMP extends BookEJB { private DataSource dataSource_; private EntityContext ctx_;

v020402

Entity Beans

65

Implement 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_; }
v020402 Entity Beans

Enterprise Java

66

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) {} } v020402 Entity Beans }

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

Implement 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 { }
v020402 Entity Beans

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

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 {... } v020402 Entity Beans }

Enterprise Java

75

Configure Deployment Descriptors (ejb-jar.xml)

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

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>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

Entity Bean Performance Issues

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

Entity Bean Summary


Models persistent state in database Facilitates declarative persistence BMP vs. CMP Performance implications
wrap calls to entity beans with session beans

Enterprise Java

v020402

Entity Beans

80

You might also like