Using the EJB Container


BEA WebLogic Server provides a subsystem known as the EJB container . All Enterprise JavaBeans exist within this container. Through the EJB container, the application server provides services to allow the EJB to perform database management, transaction management, and life-cycle management. The bean writer has the option to use the EJB container to perform Container-Managed Persistence (CMP). The alternative is Bean-Managed Persistence (BMP), which requires the bean to directly interface with the database to implement persistence. The two types of entity beans, CMP and BMP, will be covered in detail along with the additional services provided by the EJB container. The container also provides Container-Managed Transactions (CMT) and Container-Managed Relationships (CMR). The combination of CMP with CMR greatly reduces the need for the bean provider to write Bean-Managed Persistence. This option frees the entity bean from providing the code to perform these services on its own behalf .

Note

The entity EJB type is defined by the method that is used for persistence: Bean-Managed Persistence or Container-Managed Persistence.


A BMP entity EJB contains the JDBC code in its methods to directly communicate with the database. A CMP entity EJB allows the application server to perform persistence through the EJB container. In either case, the persistent state of the entity bean is stored in a relational database by mapping the attributes of the bean to rows and columns in the tables of a relational database. Both BMP and CMP EJBs provide a deployment descriptor in the form of an XML file to describe the components of the bean and the type of persistence that will be used. In the case of Container-Managed Persistence, the fields whose persistence is managed by the container are also specified in the deployment descriptor.

Container-Managed Persistence Versus Bean-Managed Persistence

Container-Managed Persistence is the preferred implementation for entity beans. The first motivation is that there is far less code for the bean provider to write. This reduces development time and simplifies software maintenance. The portability and reusability of the entity EJB are also increased because the interaction with the database is not hard-coded into the EJB. The EJB class and the deployment descriptor define the specification for the CMP entity bean. An entity EJB using CMP will provide <cmp-field> tags in its deployment descriptor for each field being persisted by the container. The corresponding setters and getters for the container-managed fields in the EJB class are written as abstract methods. The "Container-Managed Persistence Example" section later in this chapter contains sample code using abstract setters and getters. Container-Managed Persistence is generally used in conjunction with Container-Managed Relationships. The need for CMR arises when an entity bean has another entity bean as an attribute. The container must perform the loading and persistence of the encapsulated entity beans as well. The composition relationship between entity beans is specified using CMR. CMP with CMR greatly reduces the need to implement Bean-Managed Persistence.

The primary advantage of implementing BMP is having flexibility and control over persistence. Having this control over the implementation of persistence allows the bean provider to use vendor-specific extensions or stored procedures. The debugging of problems with persistence is simpler with BMP because the interaction with the database is in the entity bean, rather than in the container. In addition, the implementation may contain particularly complex relationships between the objects being persisted. For example, if very complex many-to-many relationships exist between objects, using BMP is often necessary. Another need for BMP occurs when a proprietary scheme is being used for the stored data. This is the case if something other than a relational database supported by the WebLogic Server is being used for data persistence.

Tip

The persistence type is a per-bean property. This means that the same application can have both CMP and BMP entity beans. There are specific advantages to each methodology. The application should exploit the advantages of the persistence mechanisms that best suit the entity bean.


Note

A BMP entity bean cannot be used in a container-managed relationship. Both entities playing a role in the container-managed relationship must be implemented using CMP.


Container-Managed Relationships

The Enterprise JavaBeans 2.0 specification introduced Container-Managed Relationships. This new capability of the container, to manage complex relationships between objects, greatly reduced the need for bean providers to implement Bean-Managed Persistence. Prior to the availability of CMR, the only way to maintain complex relationships in persistent storage was for the bean providers to do it themselves , hence BMP. CMR enhances the services provided by the container, allowing the object relationships to be specified in the ejb-jar.xml deployment descriptor with the <relationships> tag. Now CMP working hand in hand with CMR can fully specify the object-to-relational mapping in the deployment descriptor rather than the bean provider implementing these relationships in the Java code of the entity bean.

The design model that is directly addressed by CMR is a composition or aggregation relationship between entity beans. In UML terminology, this is referred to as the "has" relationship between two or more entity beans. The situation occurs when an entity bean has another entity bean as one of its attributes.

For further information on composition and aggregation class relationships, see "Association Relationships," p. 108 .


Prior to the availability of CMR, the container did not handle the persistence or loading of the contained entity beans. The bean provider had to either write additional code in the ejbCreate() , ejbActivate() , and ejbPassivate() methods when using CMP, or write the entire entity bean using BMP. When the composition between entity beans forms an aggregate relationship where the life cycle of the dependent object couldn't exist outside of the context of the independent object, the implementation of ejbStore() , ejbLoad() , and ejbRemove() also requires specific code to persist and restore the dependent entity bean. The EJB 2.0 specification alleviates this situation through Container-Managed Relationships.

Refer to the section "Container-Managed Persistence Example" later in this chapter for a complete description of the EntityBean interface for CMP.

The container-managed fields of the entity bean do not appear directly in the entity bean as attributes. Instead, abstract getters and setters are used to identify the fields that are under the control of Container-Managed Persistence. The deployment descriptor contains <ejb-relation> tags to specify the multiplicity of the relationship. A relationship with multiplicity one will return the local interface of the contained entity bean. When the multiplicity of the relationship is many , the return type for the getter is specified as either java.util.Collection or java.util.Set .

Listing 21.1 shows a snippet from the ejb-jar.xml deployment descriptor specifying a relationship between a shopping cart and books. This is a one-to-many relationship: one shopping cart has many books. The relationship being established is a ShoppingCart with a collection of Books as an attribute that is also entity beans. CMP is used for the persistence of both the ShoppingCart and the Books . A container-managed relationship requires the specification of two relationship roles describing the relationship from the perspective of each entity. The ShoppingCart-Has-Books role has a mulitiplicity of many. The Book-Has-ShoppingCart role has a mulitiplicity of one.

Listing 21.1 The ejb-jar.xml Deployment Descriptor Specifies Container-Managed Relationships in the <relationships> Tag
 <relationships>     <ejb-relation>       <ejb-relation-name>ShoppingCart-Book</ejb-relation-name>       <ejb-relationship-role>         <ejb-relationship-role-name>ShoppingCart-Has-Books</ejb-relationship-role-name>         <multiplicity>many</multiplicity>                 <relationship-role-source>           <ejb-name>BookStore</ejb-name>         </relationship-role-source>         <cmr-field>           <cmr-field-name>cart</cmr-field-name>         </cmr-field>       </ejb-relationship-role>       <ejb-relationship-role>         <ejb-relationship-role-name>Book-Has-ShoppingCart</ejb-relationship-role-name>         <multiplicity>one</multiplicity>                 <relationship-role-source>           <ejb-name>ShoppingCart</ejb-name>         </relationship-role-source>         <cmr-field>           <cmr-field-name>books</cmr-field-name>           <cmr-field-type>java.util.Collection</cmr-field-type>         </cmr-field>       </ejb-relationship-role>     </ejb-relation>   </relationships> 

Container-Managed Transactions

Transaction management specifies when a transaction is started, suspended , resumed, committed, and rolled back. This is referred to as the demarcation of transactions. The proper use of transactions is key to maintaining reliable persistent data that can be trusted to be accurate. To ensure that the data is accurate in the database, before a group of updates is performed on the database, a transaction is started. If all updates complete successfully, the transaction is committed; otherwise , a rollback forces all updates to be discarded as a group. This guarantees that no partial modifications are made to the data. Either all updates are performed, or none are performed. Transaction management is performed using the Java Transaction API (JTA).

For further information on transactions, see Chapter 16, "Managing Java Transactions Using JTA," p. 527 .


You don't need to compare container-managed transactions versus bean-managed transactions with respect to entity beans. The EJB 2.0 specification requires that all entity EJBs use container-managed transactions. Session beans and servlets are allowed to perform bean-managed transactions by directly starting transactions through the javax.transaction.UserTransaction object. All entity beans, whether BMP or CMP, must use container-managed transactions. The following methods must therefore never be used in an entity bean:

  • commit() , setAutoCommit() , and rollback() methods of java.sql.Connection

  • getUserTransaction() method of javax.ejb.EJBContext

  • Any methods of javax.transaction.UserTransaction

The XML deployment descriptor contains the declarative rules for specifying transaction demarcation. Six keywords are used to specify the rules for transaction demarcation. The transaction is applied on a per-method basis of the entity bean. The deployment descriptor allows a wildcard specification of the method name to set the same default transaction management to all methods of the entity bean. Individual methods may still override the default behavior by setting a different transaction attribute for those methods. Table 21.1 lists the transaction attributes.

Table 21.1. Keyword Definitions for Transaction Attributes

<trans-attribute>

 

Keyword

Definition

Never

The method call never participates in transactions. If the method is called within a transaction, the EJB container throws RemoteException.

NotSupported

The method call never participates in transactions. If the method is called within a transaction, the EJB container suspends the transaction during the method call and resumes the transaction when the method completes.

Supports

The method call participates in the transaction if one has been started.

Mandatory

The method call must participate in a transaction. If a transaction has not been started, the EJB container throws TransactionRequiredException.

Required

If a transaction has already been started, the method call will participate in that transaction; otherwise, the EJB container will start a new transaction.

RequiresNew

The EJB container always starts a new transaction for the method call. The new transaction is committed when the method call completes.

Note

The default transaction attribute for the BEA WebLogic Container is Supports .


The deployment descriptor, ejb-jar.xml , defines the attributes for container-managed transactions. Listing 21.2 shows a snippet from a deployment descriptor that specifies the Required transaction attribute for all methods in the ShoppingCartEJB entity bean. The <container-transaction> elements are children of the < assembly-descriptor > .

Listing 21.2 Sample Snippet of a Container Transaction from ejb-jar.xml
 <container-transaction>   <method>     <ejb-name>ShoppingCart</ejb-name>     <method-name>*</method-name>   </method>   <trans-attribute>Required</trans-attribute> </container-transaction> 

Individual methods of the ShoppingCart entity bean may override the default transaction attribute by adding additional <container-transaction> specifications as children of the <assembly-descriptor> (see Listing 21.3).

Listing 21.3 Container Transaction for a Specific Method
 <container-transaction>   <method>     <ejb-name>ShoppingCart</ejb-name>     <method-name>addBook</method-name>     <method-params>       <method-param>com.objectmind.BookStore.BookEntityVO</method-param>     </method-params>   </method>   <trans-attribute>Supports</trans-attribute> </container-transaction> 

Container-managed transactions are demarcated on method call boundaries. The transaction attribute specifies the action performed by the EJB container when the method is called. If a new transaction is started, the transaction is committed when the method returns.

Rolling Back Container-Managed Transactions

The transaction demarcation is defined by the <trans-attribute> specification for the methods of the entity bean. Every transaction is either committed or rolled back. The EJB container will roll back container-managed transactions under two conditions. First, if a RuntimeException is thrown after the transaction is started, the transaction is automatically rolled back. Second, invoking the setRollbackOnly() method on the EJBContext enables the bean provider to cause a rollback when an application-specific exception is thrown. For example, the BookStoreEJB will roll back the transaction if the requested book is out of stock in the purchase method. Entity beans are provided with the javax.ejb.EntityContext through their setEntityContext() and unsetEntityContext() methods.

For example, the purchase() method for a BookStoreEJB is written, as shown in Listing 21.4, to throw an application-specific exception and roll back the container-managed transaction if the book is out of stock.

Listing 21.4 The setRollbackOnly() Method of EJBContext Is Used to Roll Back a Container-Managed Transaction
 public void addBook(BookEntityVO bookData)         throws NamingException, CreateException, FinderException     {         try         {             // use JNDI to lookup the Home interface for Book             Context jndiContext = new InitialContext();             BookEntityHome bookHome =                 (BookEntityHome)jndiContext.lookup("cmp.BookEntity");             // make sure the book is in stock before adding             // it to the shopping cart             BookEntity book =                 bookHome.findBookByTitle( bookData.getTitle() );             // create a new Book entity             book = bookHome.create(bookData);             // add the Book reference to our book list             Collection books = getBooks();             books.add(book);         }         catch( FinderException x )         {             ctx.setRollbackOnly();             throw x;         }         catch( RemoteException x )         {         }     } 

Tip

After a transaction has been set to the "rolled back" state, all persistent activities thereafter will be rolled back for this transaction. Therefore, as a best practice the bean provider might want to check the state of the transaction using the getRollbackOnly() method on the EJBContext before further processing.




BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net