Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.setString(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), and 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, 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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020