Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Web Development

A Universal Model for Designing the Entity EJB Layer


Jun01: A Universal Model for Designing the Entity EJB Layer

Jonathan, Michael, and Andrei are developers for FCG Doghouse and can be contacted at [email protected], [email protected], and apovodyrev@ doghouse.com, respectively.


Enterprise JavaBeans (EJB) is an industry standard for creating scalable, robust component architectures in Java. In particular, entity EJBs — the components that represent data stores as Java objects — offer an attractive architecture for accessing an application's data because the EJB container supports them with robust services for persistence, security, distribution, and scalability. In practice, however, we have found several limitations with the conventional use of the EJB architecture, particularly with respect to entity EJBs, that make the use of this technology undesirable for many projects. Some of these limitations include:

  • Inconsistent implementations of the EJB standards by various application servers. (In general, application servers do not implement synchronization, data caching, or object management in similar fashions, which increases the complexity of knowing how to implement these objects efficiently.)
  • The need to maintain multiple Java classes (files include the home interface, the remote interface, the bean class, and possibly the primary key class) plus a deployment descriptor to represent a single business entity.

  • The potential for excessive database querying for synchronization purposes.

  • Definition of query parameters in a nonSQL-based language in the entity EJB deployment descriptor file. (As of EJB 2.0 this restriction may not be as crucial as the deployment descriptors become more universal, but the deployment descriptor will still create additional complexities for maintaining the entity EJB.)

This raises the question: How can we implement entity EJBs in an efficient, maintainable, and flexible manner?

Entity EJBs

To provide flexibility, entity EJBs come in two varieties, container-managed (CMP) and bean-managed persistent (BMP). CMP-entity EJBs provide simpler implementation by hiding many of the details behind data access and synchronization. You still need to create the home interface, remote interface, bean class, deployment descriptor, and primary key class. However, you do not need to specify any SQL code for ejbLoad() and ejbStore(). The SQL for those functions is generated for you based on the information provided in the deployment descriptor. This turns out to be a double-edged sword. On one hand, you can rapidly develop entity EJB objects that map to single tables, but you lose the ability to manage how data is accessed. Also, you cannot represent multiple database tables, multiple databases, or other complex data relationships with these components. (Better support for simple table joins is proposed in the EJB 2.0 specification, but it is unclear how application servers will ultimately implement this feature.)

BMP-entity EJBs are provided as an alternative to CMP-entity EJBs. The primary difference here is that the code necessary for data synchronization is left to the developer to provide. BMP lets you implement your own data synchronization standards (such as lazy-loading and smart-storing) and provide a component that can represent complex data relationships. However, you still have to maintain a minimum of four files to define each entity EJB and also the SQL code. All of this increases the time required to develop an entity EJB.

So the real problem is not the flexibility of EJB, but that the conventional EJB architecture is too time consuming and maintenance intensive to use in many applications. Considering this problem, we identified an implementation model that leverages the services provided by the container while reducing the number of files needed to define an entity EJB. As a result, our model provides a strategy for implementing entity EJBs that should make it easier and more practical for you to use them on your project.

The Model: An Overview

Our architecture is based on the BMP-entity EJB model because of its flexibility. The challenge with BMP is to simplify the development process. To accomplish this, we created a single universal BMP-entity EJB, the Universum Bean, because it eliminates the need to develop an EJB for every business entity. Additionally, any special implementation rules for a system can be incorporated into the Universum Bean classes. The development effort for an application is then centralized in the development of classes that implement the EJB functionality. The client passes these classes to the Universum Bean at run time to complete the business entity. Of all the candidates for this role, the EJB primary key class seemed ideal for the business entity implementation.

We see the new primary key role taking two forms. The first offers the flexibility of the BMP-entity EJB where you specify the insert, update, delete, and select queries necessary to manage the data. The second mimics the capabilities of a CMP-entity EJB, letting users specify the table and columns to represent and leaving the SQL generation to the provided code. For the purposes of this article, we could only cover a specific example of the first model; however, the example business entity provided is a good foundation for abstracting the full SQL generation capabilities.

So what are we saying? Using the BMP-entity EJB as a performance-based platform, you can design a robust EJB architecture that is fast to develop, easy to maintain, and consists of a single, universal entity EJB and thereafter requires the development of just one class — the primary key class per business entity (see Figure 1).

The Universum Bean

Conventionally, the primary key class serves a single purpose: to represent the unique identifier for the data record. By adding new features to this much-neglected player, you can transform it into a complete data access object (DAO). The primary key interface (see Listing One) decouples the business entity from the EJB. (The complete source code and related files for the universal object class are available electronically; see "Resource Center," page 5.)

In this paradigm you only need one entity EJB deployed. It remains fully tested and packaged, requiring no development work when adding new business entities. The EJB simply acts as a proxy for the primary key class.

The Home Interface

By the EJB specification we are required to define a findByPrimaryKey() method in the home interface (see Example 1). Beyond this we added a create() method and a flexible finder method called findBySQLWhere() that can be used to implement any other specific finder methods defined in the primary key classes; see Example 2. (Why do we define specific finder methods? We'd like to shield the client from having to write SQL code when the object can present a complete programmatic interface. Furthermore, while using findBySQLWhere() in the client offers flexibility, it also binds the client to the business entity's implementation.) Considering that the Universum Bean is not bound to any particular business entity, it needs a DAO to implement the "create" and "finder" methods. In this model, the primary key is the DAO and must be passed to each of the methods defined in the home interface.

The Universal Value Object and Remote Interface

Universum Bean offers coarse-grained data operations by using the value object UniversumData as a transport for its properties. (For details on Sun's Value-Object pattern see http://developer.java .sun.com/developer/restricted/patterns/ ValueObject.html and http://www.javasoft.com/j2ee/blueprints/.) This approach has the advantage over fine-grained data operations (remote get and set methods per property) of reducing network traffic when working with EJB properties in bulk. In addition, we have defined a value object that is not tailored to any specific business entity (Listing Two). The result is a flexible and efficient model that makes it easy to define a universal EJB remote interface consisting of just two methods: getBeanAttributes() and setBeanAttributes() (see Example 3).

The Bean Implementation Class

The bean class (available electronically) uses methods provided on the primary key interface to implement a smart-storing data management scheme. In this scheme, a "dirty" flag, stored in the EJB, is set whenever the setBeanAttributes() method is called. When the container calls ejbStore(), this flag determines whether to call the insert/update query. This technique avoids excessive database querying associated with CMP-entity EJBs, notorious for "eager" data synchronization. (The smart-storing scheme may not be suitable for all application environments such as clustered environments. However, the model permits you to modify the bean implementation to support your environment.)

Pulling It Together

Once you have deployed Universum Bean to the server, it's time to develop specific business entities. A primary key class represents each business entity in the application, so lets look at a sample implementation.

Implementing the Primary Key

Figure 1 shows a few example primary keys along with the Universum Bean class relationships. As indicated, each primary key class you develop must implement the UniversumPK interface. You must provide the database access logic and implement any additional finder methods you want. (Any specific finder method, like findByName(), is implemented as a static method, allowing the client to manage the home interface reference as required by the application; see Example 2.) In addition, specific rules regarding the validation of the UniversumData objects must be provided in the class. An example primary key, UserPK, is available electronically; see "Resource Center," page 5.

Client Access

Example 4 shows how a client uses Universum Bean and the UserPK business entity to perform common operations. In this example, the client creates a UniversumData object and inserts the data elements for the business entity. Then the client retrieves the "FirstName" data element. Finally, the business entity is updated with a new "Phone" number; see Figure 2.

Conclusion

EJB technologies provide a robust, scalable, and distributable platform that can enhance the capabilities of most systems. An alternative to conventional CMP- and BMP-entity EJBs is the Universum Bean model that leverages inherent benefits while reducing the impact on development time and improving maintainability of your system.

Some of the key benefits of the Universum Bean model are:

  • Built-in value object for better network utilization.
  • Aggregation of database tables into business entities.

  • Simplification of EJB maintenance and deployment.

  • Reduction in the number of classes needed to produce an EJB application.

  • Possible enhancement in performance by requiring fewer EJB instance pools on the application server.

As with most design patterns there are constraints. Universum Bean restricts your option to associate a deployment descriptor (transaction isolation levels or security) with each business entity because there is only one entity EJB. Although the entity EJB is deployable using different deployment descriptors, in general, this model is not an optimal solution for EJB systems with diverse transactional, resource, or security requirements. However, there is no reason why conventional approaches cannot be combined with Universum Bean to gain performance and reduce development time.

With a little more effort, Universum Bean can support rapid application development with the addition of a SQL generator class. Combine this with an extension that maps SQL names to property names, and the Universum Bean model will rival the ease of developing CMP-entity EJBs.

Acknowledgment

We would like to thank FCG Doghouse for all of the support and Shameem Sait who has inspired and encouraged us to write this article.

DDJ

Listing One

package org.article.entitybean;
import java.sql.*;
import org.article.util.UniversumData;
import java.util.*;

/* Universal EJB primary key class that defines an interface that each 
 * concrete primary key class must implement.
 * @version: 1.0
 * @author: Andrei Povodyrev
 */
public interface UniversumPK    extends java.io.Serializable{
    public int hashCode(); //required by EJB specs   
    public String toString(); //required by EJB specs
    /* Implement this to determine primary key equality with another of 
     * same type, required by EJB specs
     * @param   obj  another UniversumPK
     * @return     true if the primary keys are the same
     */
    public boolean equals(Object obj);   
    public UniversumPK insert(UniversumData beanAttributes, Connection con)
        throws SQLException;
    /* Called to delete the row represented by this primary key
     * @exception   SQLException  
     */
    public void delete(Connection con) throws SQLException;

    /* Called to update the row represented by this primary key
     * @exception   SQLException  
     */
    public  void update(UniversumData beanAttributes, Connection con)
        throws SQLException;

    /* Called to select the row represented by this primary key
     * @return UniversumData
     * @exception   SQLException  
     */         
    public UniversumData select(Connection con) throws SQLException;

    /* Called to test for existance of the record represented by 
     * this primary key
     * @return     true if the record exists
     * @exception   SQLException  
     */
    public boolean exists(Connection con) throws SQLException;     
    /* Finds records using a SQL where clause
     * @param   where  the SQL where clause
     * @return     an enumeration of records
     * @exception   SQLException  
     */
    public Collection findBySQLWhere(String where, 
                                     Connection con) throws SQLException;
    /* Validates entry data which keys must match those specified by 
     * the concrete primary key class
     * @return     true if entry data valid
     **/
    public boolean validate(UniversumData attributes)throws SQLException;  
    }

Back to Article

Listing Two

package org.article.util;
import java.util.*;
/* Sun's recomendation for value objects: 
 *  fine-grained, dependent, i.e controlled by another object,
 *  and immutable, i.e. fields are not independently modifiable **/
public class UniversumData implements java.io.Serializable, Cloneable
{
    private HashMap _attributeMap;
    public UniversumData(HashMap map){      this.setMap(map);   }
    protected void setMap(HashMap map) { _attributeMap = map;   }
    public HashMap getMap(){        return _attributeMap;   }
    public Object get(String key){
        return _attributeMap == null?null:_attributeMap.get(key);   
  }
    public Object clone() throws CloneNotSupportedException{ 
// implement clone ...
    }

Back to Article


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.