Patterns and Idioms

Yesterday, you saw some patterns and idioms that apply to writing Session beans. In this section, you will see some more that relate to BMP Entity beans and local interfaces. If you are impatient to get onto the exercise, feel free to skip this section and revisit later.

Interfaces, Façades, and State

This is a pattern that relates mostly to Session beans, but is discussed today rather than yesterday because it uses local interfaces.

While Session beans can provide both a remote and a local interface, you'll only want to provide one or the other more often than not. Generally, you should aim to have a small number of Session beans that offer a remote interface, and the remainder will be local “helper” beans. In design pattern terms, the remote Session beans create a Façade. This pattern is discussed more fully on Day 18, “Patterns.”

The Façade beans will likely be stateful. Certainly, the helper beans should not be stateful, because chaining stateful objects is poor design, as noted yesterday.

Use Local Interfaces for Entity Beans

Entity beans should only ever be accessed through a local interface, and there are some very good reasons for this.

First, accessing Entity beans through a remote interface implies network traffic and the cost of cloning serializable objects. When the client runs in the same JVM as the Entity bean, a local interface eliminates cost.

This ties in with the previous discussion on Session bean interfaces and façades. Session beans provide a remote interface to the enterprise application, so Session beans should act as a front-end to Entity beans. Some people think of this as the verb/noun paradigm—the Session beans are the verbs (the doing end of the application) and the Entity beans are the nouns (the reusable business objects within some domain). Defining only local interfaces to Entity beans effectively enforces this pattern.

Second, finder methods of Entity beans—already expensive to use—become even more so when the client is remote. This was remarked on earlier today.

Lastly, and perhaps most significantly, local interfaces are the cornerstone of container-managed relationships (CMR)—part and parcel of container-managed persistence. You'll be learning all about this tomorrow. If you build your BMP beans using local interfaces, you provide a migration path to implementing those beans using CMP in the future.

Dependent Value Classes

Under BMP, the Entity bean's state can be represented in any way that is appropriate. Moreover, the bean can persist this state, in any way it wants.

Sometimes, a bean's state will be simple enough (that is, just a set of scalar fields) that it will correspond to a row in an RDBMS table. More often though, some of those fields will be vector, and they might even include some complex data, such as a map or photo and so on.

One simple solution to persisting such objects is to ensure that the fields of the bean are either scalar primitives or are a reference to a serializable object, an instance of what are sometimes called dependent value classes. The structure of that object can be as complex as needed, so long as it is serializable. The scalar fields are stored in regular columns in the RDBMS table, and the serializable object is stored as a binary large object (BLOB).

For example, the Job bean is mapped to both the Job and JobSkill table in the case study, accessing both in its ejbLoad() and ejbStore() methods. The JobBean.skills field is a List of SkillLocal references.

An alternative design would be to store the skills list as a BLOB in the database. The Job table would be redefined to be something like the following:

create table Job
(ref varchar(16),
 customer varchar(16),
 description varchar(512),
 location varchar(16),
 skills long varbinary       -- store a BLOB in Cloudscape
)

There is then a one-to-one mapping between an instance of the Job Entity bean and a row in the Job table. One slight complication is that because the JobBean.skills field contains references to SkillLocal references, which are not necessarily serializable, the skills variable would not be serializable either. So, in the ejbStore() method, a List of skill names (that is, primary key to each SkillLocal) would be created and saved to the database. This List of skill names is the “dependent value class.”

stmt = con.prepareStatement( "UPDATE Job SET description = ?, location = ?, skills = ?
 WHERE ref = ? AND customer = ?");
stmt.setString(1, description);
if (location != null) {
    stmt.setString(2, location.getName());
} else {
    stmt.setNull(2, java.sql.Types.VARCHAR);
}

List skillNameList = new ArrayList();
for(Iterator iter = this.skills.iterator(); ) {
    skillNameList.add( ( (SkillLocal)iter.next() ).getName() );
}
stmt.setBlob(3, skillNameList);

stmt.setString(4, ref);
stmt.setString(5, customerObj.getLogin());
stmt.executeUpdate();

Conversely, in the ejbLoad(), the List of skill names would be converted back to a List of SkillLocal references. The SELECT statement would be as follows:

stmt = con.prepareStatement(
"SELECT description,location,skills FROM Job WHERE ref = ? AND customer = ?");

and the processing of the result set would be

this.description = rs.getString(1);

String locationName = rs.getString(2);
this.location = (locationName != null)? locationHome.findByPrimaryKey(locationName):null;

List skillNameList = (List)rs.getBlob(3);
this.skills =   skillHome.lookup(skillNameList);

The skillHome.lookup() home method of the Skill bean does the actual conversion from name to SkillLocal. (In fact, this method is actually used in JobBean's ejbLoad() method, so you can check out the code yourself).

This approach can substantially reduce the coding effort, although you should also be aware of some of the downsides:

  • First, the BLOB field is effectively atomic; even if just a small piece of information is changed (for example, a new skill is added), then entire BLOB must be replaced.

  • Furthermore, information previously easily accessible can now only be accessed through a single route. In the previous example, the data that was previously in the JobSkill table is now buried within the Job.skills field. It is no longer possible to perform an efficient SQL SELECT to find out which jobs require a certain skill. Instead, such a query will involve instantiating and then querying every Job bean instance.

  • Last, the data in the persistent data store is stored in Java's own serializable format. While this is a well-defined structure, it nevertheless makes it non-trivial for non-Java clients to access this data.

Note

It is possible to serialize Java classes in a custom-defined manner (for example, as an XML string) by either providing a readObject() and writeObject() method or by implementing java.io.Externalizable and implementing readExternal() and writeExternal() methods. However, such an approach would probably involve more development effort than had been saved by using a BLOB to store the dependent value class.


Because dependent value classes are serializable, it is also possible to use them as the return types of accessor methods (getters and setters) of the interface. Indeed, prior to the introduction of local interfaces in EJB 2.0, this was a recommended pattern to minimize network traffic across the Entity bean's remote interface. However, provided that only local interfaces are provided (and especially if using CMP), there is nothing wrong with providing fine-grained access to the values of the Entity bean. In effect, this design pattern has been deprecated with EJB 2.0.

Self-Encapsulate Fields

In the case study BMP beans, the private fields that represent state are accessed directly within methods. For example, the following is a fragment of the JobBean.ejbCreate() method:

public JobPK ejbCreate (String ref, String customer) throws CreateException {

    // database access code omitted

    this.ref = ref;
    this.customer = customer;
    this.description = description;
    this.location = null;
    this.skills = new ArrayList();

    // further code omitted
}

Some OO proponents argue that all access to fields should be through getter and setter accessor methods, even for other methods of the class. In other words, the principle of encapsulation should be applied everywhere. Using such an approach, the ejbCreate() method would be as follows:

public JobPK ejbCreate (String ref, String customer) throws CreateException {

    // database access code omitted

    setRef(ref);
    setCustomer(customer);
    setDescription(description);
    setLocation(null);
    setSkills(new ArrayList());

    // further code omitted
}

Some people find this overly dogmatic, and, indeed, the code in the case study takes the more direct approach. However, you may want to consider self-encapsulation because it makes BMP beans easier to convert to CMP. As you will see tomorrow, all accessing to the Entity bean's state must be through accessor methods.

Don't Use Enumeration for Finders

The EJB 1.0 specification was introduced before J2SE 1.2, so the specification allowed finder methods that returned many instances to return java.util.Enumeration instances. For backward compatibility, the EJB 2.0 specification still supports this, but you should always use java.util.Collection as the return type for finder methods returning more than one Entity bean instance.

Acquire Late, Release Early

In conventional J2SE programs, the idiom usually is to connect to the database at the start of the program when the user logs in, and only disconnect when the user logs out. Holding onto the open database connection while the user logs in substantially improves performance; database connections are relatively expensive to obtain. So, for J2SE programs, the mantra is “Acquire early, release late.”

With J2EE programs, things are inverted. The database connection should be obtained just before it is required, and closed immediately after it has been used. In other words, “Acquire late, release early.” This is shown in the Job bean, as shown in Listing 6.16.

Listing 6.16. Acquire Late, Release Early, as Shown in JobBean
 1: package data;
 2:
 3: import javax.ejb.*;
 4: import java.sql.*;
 5: // imports omitted
 6:
 7: public class JobBean implements EntityBean
 8:
 9:     public void ejbLoad() {
10:         JobPK key = (JobPK)ctx.getPrimaryKey();
11:         Connection con = null;
12:         PreparedStatement stmt = null;
13:         ResultSet rs = null;
14:         try {
15:             con = dataSource.getConnection();
16:             stmt = con.prepareStatement( ... );
17:
18:             // SQL code omitted
19:
20:         }
21:         catch (SQLException e) {
22:             error("Error in ejbLoad for " + key, e);
23:         }
24:         catch (FinderException e) {
25:             error("Error in ejbLoad (invalid customer or location) for " + key, e);
26:         }
27:         finally {
28:             closeConnection(con, stmt, rs);
29:         }
30:     }
31:     // code omitted
32: }

The reason that this works is because the database connection is obtained from a javax.sql.DataSource (line 15) in a J2EE environment, rather than using the java.sql.DriverManager.getConnection() method. Obtaining connections from DataSources is not expensive in performance terms because they are logical connections, not physical connections. When such a connection is obtained, it is merely obtained from a connection pool, and when it is “closed,” it is simply returned back to the connection pool.

Indeed, using the J2SE idiom of acquire early, release late (for example, by obtaining a connection in setEntityContext() and releasing it in unsetEntityContext()) can adversely affect performance, because every instantiated bean would have its own database connection. This may well reduce application throughput because the memory resources of both the EJB container and the database server would be increased to handle many open database connections. In comparison, the J2EE idiom means that the number of database connections open is no more than the number of methods concurrently executing.

Business Interface Revisited

Yesterday, you learned about the business interface idiom, whereby the business methods are pulled out into a separate interface such that the bean itself can implement this interface. This principle can equally be applied to Entity beans using local interfaces, as shown in Figure 6.10.

Figure 6.10. Business interfaces can be applied to Entity beans with local interfaces.


There is one difference when applying this technique to beans that only have local interfaces; there is no longer any need for the methods of the business interface to throw RemoteException, because the local interface of the bean (JobLocal in Figure 6.10) is not itself remote. Even so, the bean still does not implement its local interface because the methods of the EJBLocalObject interface are there to be implemented by the local proxy object, not by the bean.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.66.94